When you want to deploy your application to tomcat server , you may do it using admin UI but how can you access it? Do you know default admin password?
Actually tomcat does not provide any default password. You need to add users to $TomcatHome/conf/tomcat-users.xml and provide role as manager-gui(For tomcat 7 and 8) and manager (For tomcat 6).

Default tomcat-users.xml

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>
As you can see, there are no users defined in above xml.You can simply add user as below:

tomcat-users.xml

<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->

<role rolename="manager-gui"/>
<user username="arpit" password="arpit" roles="manager-gui"/>
</tomcat-users>
You need to use role as manager-gui for tomcat 7, tomcat 8 and manager for tomcat 6

In this post, we will see how to send HTTP Get/Post in java.
There are many times when you need to send http get or post request. You can use HttpURLConnection for sending get/post request in java. It belongs to java.net package.

HttpURLConnection example:

We are going to send get or post request to URLs used in restful web services CRUD example, so instead of using PostMan , we will send request using java.

Get Url:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
It will give you list of country in json format.

Post URL:

http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post data:{"id":5,"countryName":"USA","population":8000}
It will create a new country resource and add it to list of counties.
Java code:
package org.arpit.java2blog.corejava;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {

 private final String USER_AGENT = "Mozilla/5.0";

 public static void main(String[] args) throws Exception {

  HttpURLConnectionExample http = new HttpURLConnectionExample();

     // Sending get request
  http.sendingGetRequest();
  
    // Sending post request
  http.sendingPostRequest();

 }

 // HTTP GET request
 private void sendingGetRequest() throws Exception {

  String urlString = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  
  URL url = new URL(urlString);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();

  // By default it is GET request
  con.setRequestMethod("GET");

  //add request header
  con.setRequestProperty("User-Agent", USER_AGENT);

  int responseCode = con.getResponseCode();
  System.out.println("Sending get request : "+ url);
  System.out.println("Response code : "+ responseCode);

  // Reading response from input Stream
  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();

  //printing result from response
  System.out.println(response.toString());

 }
 
 // HTTP Post request
 private void sendingPostRequest() throws Exception {

  String url = "http://localhost:8080/JAXRSJsonCRUDExample/rest/countries";
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type","application/json");

  String postJsonData = "{\"id\":5,\"countryName\":\"USA\",\"population\":8000}";
  
  // Send post request
  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(postJsonData);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post Data : " + postJsonData);
  System.out.println("Response Code : " + responseCode);

  BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = in.readLine()) != null) {
   response.append(output);
  }
  in.close();
  
  //printing result from response
  System.out.println(response.toString());
 }
}
When you run above program, you will get below output:
Sending get request : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Response code : 200
[{"id":1,"countryName":"India","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000}]

Sending 'POST' request to URL : http://localhost:8080/JAXRSJsonCRUDExample/rest/countries
Post Data : {"id":5,"countryName":"USA","population":8000}
Response Code : 200
{"id":5,"countryName":"USA","population":8000}
If you comment http.sendingPostRequest(); and send only get request. You will get below output:
[{"id":1,"countryName":"India","population":10000},{"id":2,"countryName":"Bhutan","population":7000},{"id":3,"countryName":"Nepal","population":8000},{"id":4,"countryName":"China","population":20000},
{"id":5,"countryName":"USA","population":8000}]
You can see USA is added to country list.

When you are working on spring or spring mvc application, you may encounter below error message.
org.xml.sax.SAXParseException: The prefix "context" for element "context:component-scan" is not bound .
or
org.xml.sax.SAXParseException: The prefix "context" for element "context:annotation-config" is not bound .

This issue generally occurs when you do not include context namespace.
For example: Lets say you have below xml configuration file.
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd" >

    <context:annotation-config />
    <context:component-scan base-package="controller" />

</beans>
Here you might get above exception because you are missing context namespace xmlns:context here.
When you add below line in above xml.
xmlns:context="http://www.springframework.org/schema/context"
so your final xml file will look as below:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd" >

    <context:annotation-config />
    <context:component-scan base-package="controller" />

</beans>
I hope it will solve context is not bound error.

In this post , we will see how to load multiple spring bean configuration files. Sometimes, you have multiple spring bean configuration file , you may have different configuration file for service, different for business object.
When you are working on complex application, it is not good practice to have only single xml configuration, you can split it into multiple file for better maintenance.
There are two ways to do it.
  • Using application context constructor
  • Using import in xml bean

Using application context constructor:

You can simply create a String array with name of multiple configuration file and pass it application context constructor.
For example:
You can load multiple files using below code:
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"spring-service.xml",
              "spring-businessObjects.xml"});

Using import: 

You can do it using import tag too.
Lets say you have spring-service.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="fetchDataService"
class="org.arpit.java2blog.FetchDataService">
 </bean>
</beans>
You have another spring configuration called spring-businessObjects.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="businessObject"
class="org.arpit.java2blog.BusinessObject">
 </bean>

</beans>
You can simply import above two files in another xml file called applicationcontext.xml. You need to load applicationcontext.xml to load all bean objects.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <import resource="spring-service.xml" />
    <import resource="spring-businessObjects.xml " />
 </bean>

</beans>

Sometimes you need to intercept incoming request and do some preprocessing or you need to do it after completion of request. It is very much similar to filters that we use with servlet.
There are two ways to use interceptor with Spring MVC.

HandlerInterceptor Interface :

We can implement HandlerInterceptor interface to use interceptor. It has three methods which we need to implement.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) : This method is executed before request is handed over to handler method.
If you notice it has boolean return type. If this method returns true, then it will go to other interceptors or to handler method. If this method returns false then this request is handled by interceptor only and we should use response object to send back to client.

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) : This method is called when handler method has completed its process but dispatcherServlet is yet process the view. This method can be use to add some model view objects that can be used in view. It can be done by adding object to modelAndView object.

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) :  This method is called after view is render and request is completely processed.

HandlerInterceptorAdapter class:

Issue with HandlerInterceptor is that you need to implement all the methods but if you extend to abstract class called HandlerInterceptorAdapter, you can implement only those method which you want and other methods will have default implementation.

Lets implement custom interceptor example using HandlerInterceptorAdapter class.

Spring MVC interceptor example:

I am using Spring MVC hello world example here with small changes to it.
Spring MVC interceptor project structure

Adding Spring MVC dependency

Add spring dependency in pom.xml. We require spring core and spring mvc dependency here.
pom.xml 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.arpit.java2blog</groupId>
  <artifactId>SpringMVCHelloWorldExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCHelloWorldExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
   </dependency>

    <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCHelloWorldExample</finalName> 
    
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
        </configuration>
    </plugin>
    </plugins>

  </build>
   <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
   </properties>
</project>

Create Controller 

Create a package named "org.arpit.java2blog.springmvc.controller"
create a controller class named "HelloWorldController.java"
package org.arpit.java2blog.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 
 @RequestMapping("/helloworld")
 public ModelAndView hello() {
      return new ModelAndView("hello");
 }
}

Create interceptor 

create interceptor class called SampleInterceptor.java
package org.arpit.java2blog.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SampleInterceptor extends HandlerInterceptorAdapter {

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
   throws Exception {
  request.setAttribute("blogName", "java2blog");
  return true;
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
   ModelAndView modelAndView) throws Exception {
  String blogName = (String) request.getAttribute("blogName");
  // We are adding some modelAndView objects here and will use it in view jsp.
  modelAndView.addObject("blogName",blogName);
  modelAndView.addObject("authorName", "Arpit");
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  String blogName = (String) request.getAttribute("blogName");
  String authorName = (String) request.getAttribute("authorName");
  System.out.println("Request URL::" + request.getRequestURL().toString());
  System.out.println("Blog name : " + blogName);
  System.out.println("Author Name : " + authorName);
 }
}

Here I am setting request attribute(blogName) in preHandle method and we are getting it in postHandle method. We are also adding two objects to modelAndView which we will use in jsp.

Create view

Modify index.jsp as below
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
</head>
<body>
<a href="helloworld.html">Click here to read hello message </a>
</body>
</html>
Create hello.jsp in /WEB-INF/ folder
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
This is written by ${authorName} on ${blogName}
</body>
</html>

Configuring spring mvc application 

 Now we need to configure two files "web.xml" and "springmvc-dispatcher-servlet.xml" We need to declare DispatcherServlet in web.xml for spring MVC. When DisplatcherServlet is initialized,spring tries to load application context from [servlet name]-servet.xml file. So in this case, it will be try to load springmvc-dispatcher-servlet.xml.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>
create xml file named "springmvc-dispatcher-servlet.xml" in /WEB-INF folder as below.
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="org.arpit.java2blog.springmvc.controller" />
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/WEB-INF/"/>
  <beans:property name="suffix" value=".jsp" />   
 </beans:bean>
 <interceptors>
  <interceptor>
   <mapping path="/helloworld.html" />
   <beans:bean
    class="org.arpit.java2blog.springmvc.interceptor.SampleInterceptor"></beans:bean>
  </interceptor>
 </interceptors>
</beans:beans>
Here we have declared interceptor(SampleInterceptor) in above file which will intercept specific URL (/helloworld.html).

It 's time to do maven build.
Right click on project -> Run as -> Maven build
Provide goals as clean install (given below) and click on run


Run the application

Right click on project -> run as -> run on server
Select apache tomcat and click on finish

 You will see below screen:



When you click on above link, you will get below screen

We are done with Spring MVC interceptor example. If you are still facing any issue, please comment.
Download

click to begin

20KB .zip


In this post, we will see Spring AOP AspectJ Annotation examples.
If you are not familiar with Spring AOP terminology, you may go through Spring Aspect oriented programming(AOP) tutorial.
Following are the AspectJ annotations which we are going to use to implement Spring AOP.
@Aspect : To declare a class as Aspect.
Annotations which are used to create Advices are:
@Before : @Before annotation is used to create before advice. It executes before actual method execution (Join points)
@AfterReturning: This annotation is used to create return advice. It executes after a method execution completes without any exception.
@AfterThrowing: This annotation is used to create After throwing advice, it executes if method exits by throwing an exception.
@After : This annotation is used to create after advice, it executes after a method execution  regardless of outcome.
@Around : This annotation is used to create around advice,  It executes before and after a join point.

This may be confusing right now but once you implement an example, it will be clear.

@Before  :

lets say you have some business logic class (BusinessLogic.java) and you want to do logging before execution of getBusinessLogic method of this class.
package org.arpit.java2blog;

public class BusinessLogic {
 
 public void getBusinessLogic() {
  System.out.println("*****************");
  System.out.println("In Business Logic method");
  System.out.println("*****************");
 }
}
Now we will create aspect class
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

 @Before("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingBeforeBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingBeforeBusinessLogic() is running!");
  System.out.println("Before execution of method : " + joinPoint.getSignature().getName());
 }

}
execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..)) is pointcut expression. It denotes execution of method loggingBeforeBusinessLogic before exection of getBusinessLogic method of BusinessLogic class.
Lets do xml configuaration of above beans in spring-config.xml.
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

 <aop:aspectj-autoproxy />
 <bean id="businessLogic" class="org.arpit.java2blog.BusinessLogic">
 </bean>
 <!-- Aspect -->
 <bean id="logAspect" class="org.arpit.java2blog.LoggingAspect" />

</beans>
Create main class named SpringAOPMain to execute the application
package org.arpit.java2blog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAOPMain {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
        BusinessLogic businessLogic = (BusinessLogic) appContext.getBean("businessLogic");
        businessLogic.getBusinessLogic();      
    }
}
When you run above program, you will get below output:
Jul 21, 2016 10:01:14 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@24174be7: startup date [Thu Jul 21 22:01:14 IST 2016]; root of context hierarchy
Jul 21, 2016 10:01:14 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
loggingBeforeBusinessLogic() is running!
Before execution of method : getBusinessLogic
*****************
In Business Logic method
*****************

@After:

I am replacing @Before method in LoggingAspect.java with @After annotated method.This method will execute after execution of actual business logic, so LoggingAspect.java will look something like this.
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;

@Aspect
public class LoggingAspect {

@After("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
}
When you run SpringAOPMain.java again, you will get below output:
Jul 21, 2016 10:24:26 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@75783d33: startup date [Thu Jul 21 22:24:26 IST 2016]; root of context hierarchy
Jul 21, 2016 10:24:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
loggingAfterBusinessLogic() is running!
After execution of method : getBusinessLogic
As you can see in above output, loggingAfterBusinessLogic executed after getBusinessLogic method

@AfterReturning:

I am replacing @After with @AfterReturning in above LoggingAspect.java.This method will execute after execution of actual business logic but only if it successfully returns.
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class LoggingAspect {

@AfterReturning("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
}
When you run SpringAOPMain.java again, you will get below output:
Jul 21, 2016 10:24:26 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@75783d33: startup date [Thu Jul 21 22:24:26 IST 2016]; root of context hierarchy
Jul 21, 2016 10:24:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
loggingAfterBusinessLogic() is running!
After execution of method : getBusinessLogic

@AfterThrowing: 

Lets add one more method with @AfterThrowing annotation. It will execute if any exception occurs in getBusinessLogic method.
LoggingAspect.java
package org.arpit.java2blog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect {
 
 @AfterReturning("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogic(JoinPoint joinPoint) {

  System.out.println("loggingAfterBusinessLogic() is running!");
  System.out.println("After execution of method : " + joinPoint.getSignature().getName());
 }
 
 @AfterThrowing("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAfterBusinessLogicException(JoinPoint joinPoint) {

  System.out.println("Exception occurred in getBusinessLogic method");
  
 }

}
Now throw RuntimeException from getBusinessLogic to test @AfterThrowing exception. BusinessLogic.java
package org.arpit.java2blog;

public class BusinessLogic {
 
 public void getBusinessLogic() {
  System.out.println("*****************");
  System.out.println("In Business Logic method");
  System.out.println("*****************");
  throw new RuntimeException();
 }
}

When you run SpringAOPMain.java , you will get below output:
Jul 21, 2016 10:34:55 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@739474: startup date [Thu Jul 21 22:34:55 IST 2016]; root of context hierarchy
Jul 21, 2016 10:34:55 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
*****************
In Business Logic method
*****************
Exception occurred in getBusinessLogic method
Exception in thread "main" java.lang.RuntimeException
 at org.arpit.java2blog.BusinessLogic.getBusinessLogic(BusinessLogic.java:9)
 at org.arpit.java2blog.BusinessLogic$$FastClassBySpringCGLIB$$3d288cb4.invoke(<generated>)
 at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
 at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
 at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
 at org.arpit.java2blog.BusinessLogic$$EnhancerBySpringCGLIB$$1fbd989f.getBusinessLogic(<generated>)
 at org.arpit.java2blog.SpringAOPMain.main(SpringAOPMain.java:10)

As you can see loggingAfterBusinessLogicException got executed as there is exception in business logic.

@Around:

Method with @Around will get called before and after execution of business logic.
You need to call reference of ProceedingJoinPoint and call proceed method to execute actual business logic.
package org.arpit.java2blog;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class LoggingAspect {

 @Around("execution(* org.arpit.java2blog.BusinessLogic.getBusinessLogic(..))")
 public void loggingAroundBusinessLogic(ProceedingJoinPoint joinPoint) throws Throwable {
  System.out.println("Before calling actual business logic"); // Before running actual business logicic
  joinPoint.proceed(); // business logic method get executed 
  System.out.println("After calling actual business logic"); // After running actual business logic
 }
}
When you run SpringAOPMain.java , you will get below output:
Jul 21, 2016 11:04:10 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@739474: startup date [Thu Jul 21 23:04:10 IST 2016]; root of context hierarchy
Jul 21, 2016 11:04:10 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Before calling actual business logic
*****************
In Business Logic method
*****************
After calling actual business logic

In this post, we will see how to create custom exception in java. It is very simple to create custom exception in java. You just need to extends Exception class to create custom exception.
Lets understand this with example. You have list of counties and if You have "USA" in list of country, then you need to throw invalidCountryException(Our custom exception).
Example: 
Create InvalidCountryException.java as below
package org.arpit.java2blog;

public class InvalidCountryException extends Exception{

 InvalidCountryException(String message)
 {
  super(message);
 }
}
Create POJO class called Country.java
package org.arpit.java2blog;

public class Country {
 
 private String name;
 
 Country(String name ){
 this.name = name;
 }
  public String toString() {
   return name;
  }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
  
 
}

Lets create CountryCheckMain.java. This class will have main method.
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;

public class CountryCheckMain {

 public static void main(String args[]) {
  List<Country> countries = new ArrayList<Country>();
  Country indiaCountry = new Country("India");
  Country chinaCountry = new Country("China");
  Country nepalCountry = new Country("Nepal");
  Country bhutanCountry = new Country("Bhutan");
  countries.add(indiaCountry);
  countries.add(chinaCountry);
  countries.add(nepalCountry);
  countries.add(bhutanCountry);
  boolean safe;
  try {
   safe = checkListOfCountries(countries);
   if (safe)
    System.out.println("We don't have USA in list of Countries");
   Country USACountry = new Country("USA");
   countries.add(USACountry);
   checkListOfCountries(countries);
  } catch (InvalidCountryException e) {
   e.printStackTrace();
  }

 }

 public static boolean checkListOfCountries(List<Country> countries) throws InvalidCountryException {
  for (int i = 0; i < countries.size(); i++) {
   Country country = countries.get(i);
   if (country.getName().equals("USA")) {
    throw new InvalidCountryException("USA is not allowed");
   }  
  }
  return true;
 }
}

When you run above program, you will get following output:
We don't have USA in list of Country
org.arpit.java2blog.InvalidCountryException: USA is not allowed
 at org.arpit.java2blog.CountryCheckMain.checkListOfCountries(CountryCheckMain.java:37)
 at org.arpit.java2blog.CountryCheckMain.main(CountryCheckMain.java:25)

As you can see, if we have "USA" in list of Countries,we are throwing InvalidCountryException.

In this post, we will see Spring interview interview questions.If you are java/j2ee developer and have some experienced on Spring, you are going to face Spring interview questions.

Here I am sharing list of important Spring interview questions.

1. What is Spring framework?

Spring framework is an open source framework created to solve the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use. Main module for Spring are Spring core,Spring AOP and Spring MVC.

2. What are main features of Spring frameworks?

  • The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created.
  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. 
  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. 
  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

3. Explain main modules of Spring ?

  • Spring AOP:
    One of the key components of Spring is the AOP framework. AOP is used in Spring:
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP
  • Spring ORM:
    The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.  
  • Spring Web:
    The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
  • Spring DAO:
    The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
  • Spring Context:
    This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
  • Spring Web MVC:
    This is the Module which provides the MVC implementations for the web applications.
  • Spring Core:
    The Core package is the most import component of the Spring Framework.
    This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
Spring framework Architecture
Spring Framework Architecture

4. What is dependency injection(IOC) in Spring?

The basic concept of the dependency injection (also known as Inversion of Control pattern) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.
i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

5. What are ways to inject dependency in Spring?

There are two ways to do dependency injection in Spring.

6. What is Bean in Spring?

A normal POJO class managed by Spring IOC containter are called Spring beans. It is core part of Spring application.
Example:
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>

7. How can you configure Spring in your application?

There are 3 ways to do it.
  • XML based configuration
  • Java based configuration
  • Annotation based configuration.

8. What is Spring XML based configuration?

In Spring XML based configuration, you define all dependency in a XML file. You define all your beans with </bean> tag in XML file and all dependencies are read using these XML file.
for example :
Sample ApplicationContext.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>
  <bean id="CapitalBean" class="org.arpit.javapostsforlearning.Capital">
      <property name="capitalName" value="Delhi"/>
  </bean>
</beans>
You can read this ApplicationContext.xml using:
 ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

9. What is Spring java based configuration?

In Spring java based configuration, you inject all dependencies using java class only. You can use @Configuaration and @Bean annotations to do it.
package org.arpit.java2blog.config;
import org.arpit.java2blog.model.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfiguration {

 @Bean(name="countryObj")
 public Country getCountry()
 {
  return new Country("India");
 }
 
}

Above file is equivalent to below spring configuration xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<context:annotation-config/>  
 <bean id="countryObj" class="org.arpit.java2blog.Country" >
  <property name="countryName" value="India"/>
 </bean>
</beans>
To get above bean to application context, you need to use below code
ApplicationContext appContext = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
 Country countryObj = (Country) appContext.getBean("countryObj");
You can refer Spring java based configuration for complete example.

10. What is spring annotation based configuration? 

You can do dependency injection via annotation also instead of XML configuration. You can define bean autowiring using annotations. You can use @Component,@Repository,@Service and @Controller annotation to configure bean in Spring application.
Annotations wiring is not turned on by default. You need to turn it on using :
<?xml version="1.0" encoding="UTF-8"?>
<bean> 
<context:annotation-config/>  
</beans>
Once you put above code, you can start using annotation on class , fields or methods.

11. What are different bean scopes in Spring?

There are 5 types of bean scopes supported in spring
  • singleton – Scopes a single bean definition to a single object instance per Spring IoC container.
  • prototype – Return a new bean instance each time when requested
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session. 

12. What is default scope of bean in Spring?

singleton is default scope of a bean in Spring. You have to explicitly change scope of a bean if you want different scope.

13. What is ApplicationContext and what are its functions?

ApplicationContext is an central interface for providing configuration information to an application.
An ApplicationContext provides the following functionalities:
  • Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events. Implementations must provide a means of registering event listeners.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

14. How do you injection collection in Spring?

You can initialize collection using list and value tag as below:
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="listOfStates">
   <list>
    <value>Maharastra</value>
    <value>Madhya Pradesh</value>
    <value>Rajasthan</value>
   </list>

  </property>
 </bean>

15. What do you mean by bean autowiring in Spring?

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration
<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" autowire="byName">

16. What are different modes of autowiring supported by Spring?

There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.
no:
Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.
byName:
Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file and it tries to match it with name of bean in xml configuration file.
byType:
Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
contructor:
byType mode in constructor argument.
autodetect:
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

17. What is Spring AOP?

Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

18. What is Aspect, Advice, Join point and pointcut in Spring AOP?

Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name. 
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.

19. What is @Qualifier annotation in Spring?

You can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.
You can read about Spring @Qualifier annotation for more details.

20. What is @Required annotation in Spring? 

This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.
Suppose you have very large application and you get NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.
You can read about Spring @Required annotation for more details.

You may also like:
    core java interview questions web services interview questions restful web services interview questions Hibernate interview questions Java Collections interview questions Java String interview questions

This is 16 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
We have already seen Spring core tutorial before. In this tutorial, we will see concept about Spring AOP and how to implement it.

Spring AOP:

Aspect oriented Programming is programming paradigm which is analogous to object oriented programming. Key unit of object oriented programming is class, similarly key unit for AOP is Aspect. Aspect enable modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers as a crosscutting concerns.

Why AOP?

It provides pluggable way to apply concern before, after or around business logic.
Lets understand with the help of logging. You have put logging in different classes but for some reasons, if you want to remove logging now, you have to make changes in all classes but you can easily solve this by using aspect. If you want to remove logging, you just need to unplug that aspect.

AOP concepts:

Aspect: An Aspect is a class that implements concerns that cut across different classes such as logging. It is just a name. 
Joint Point : It is a point in execution of program such as execution of method. In Spring AOP, a join point always represents a method execution.
Advice : Action taken by  aspect at particular join point. For example: Before execution of getEmployeeName() method, put logging. So here, we are using before advice.
Pointcut : Pointcut is an expression that decides execution of advice at matched joint point. Spring uses the AspectJ pointcut expression language by default.
Target object : These are the objects on which advices are applied. For example: There are the object on which you want to apply logging on joint point.
AOP proxy : Spring will create JDK dynamic proxy to create proxy class around target object with advice invocations.
Weaving : The process of creating proxy objects from target object may be termed as weaving.

Types of Advices :

Advice is action taken by aspect at particular joint point.
Before Advice: it executes before a join point.
After Returning Advice: it executes after a joint point completes without any exception.
After Throwing Advice: it executes if method exits by throwing an exception.
After Advice: it executes after a join point regardless of outcome.
Around Advice: It executes before and after a join point.

You can see implementation of Spring AOP AspectJ example here.

In this post, we will see interview questions on java String. String is most important data type which we use in our programs very often.

1. Why String is declared final or immutable in java?

There are various reasons to make String immutable.
  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value
You can refer why String is immutable in java for more details.

2. How to reverse a String in java? Can you write a program without using any java inbuilt methods?

Anagrams means if two String have same characters but in different order. For example: Angel and Angel are anagrams There are many ways to do it, some of them are:
  • Using for loop
  • Using recursion
  • Using StringBuffer
Please refer to the solution at reverse a String in java

3. How to check if two Strings are anagram in java?

There are many ways to check if Strings are anagrams. Some of them are:
  1. Using String methods
  2. Using array.sort
Please refer to solution at check if two Strings are anagram in java

4. How to check if String has all unique characters in java?

There are multiple ways to find if String has all unique characters or not.
  • By using HashSet
  • Using indexOf and lastIndexOf methods of String
  • By Using ascii value of characters.
Please refer to complete solution at check if String has all unique characters.

5. How to check if one String is rotation of another String in java?

Lets say you need to check whether str1 and str2 is rotation of one another or not.
  1. Create a new String with str3= str1 + str1
  2. Check if str3 contains str2 or not.
  3. if str3 contains str2 then str2 is rotation of str1 else it is not
You can find complete solution at check if one String is rotation of another in java.

6. Write a java program to find duplicate characters in String in java?

  1. Create a HashMap and character of String will be inserted as key and its count as value.
  2. If Hashamap already contains char,increase its count by 1, else put char in HashMap.
  3. If value of Char is more than 1, that means it is duplicate character in that String.

7. Find first non repeated character in String in java?

There are may ways to find it.
Some of them are:
  • Using LinkedHashMap
  • Using indexOf and lastIndexOf methods.
Please find complete solution at find first non repeated character in  a String.

8. Find all substrings of String in java?

Java program to find all substrings of a String.
For example: If input is "abb"  then output should be "a", "b","b", "ab", "bb", "abb"
We will use String class's subString method to find all subString.
Please refer to complete solution at find all subStrings of String.

9. Find length of String without using any inbuilt method in java?

You can use try catch block for catching StringIndexOutOfBoundException and when this exception aries, you can simply return i(Index at which you will get the exception)
Please refer to complete solution at find length of String without inbuilt methods.

10. Write a java program to print all permutations of String in java?

Take out first character of String and insert into different places of permutations of remaining String recursively. Please find complete solution at how to find all permutations of String in java.

11. What is the difference between creating String as new() and literal?

If you create a String using new operator, it is not interned. It will  create new object in heap memory even if String object already exists with same content.
        String str1=new String("Java2Blog");
        String str2=new String("Java2Blog");
        System.out.println(str1==str2);
It will return false as str1 and str2 will point to different object
If you create a String using assignment operator, it goes to the String constant pool and it is interned. If you create another String with same content, both will reference to same object in String constant pool.
String str1="Java2Blog";
String str2="Java2Blog";
System.out.println(str1==str2);
It will return true as str1 and str2 will point to same object in String constant pool.

12. How many objects will be created in below code?

String str1= "java2blog";
String str2= "java2blog";
Only one object will be created and will be stored in String constant pool.

13. How do you convert String to char array in java?

You can use string's toCharArray() method to convert String to char array.

14. What is difference between StringBuffer and StringBuilder in java?

Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously. 
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

15. How many objects will be created in below code?

String str1= new String("java2blog");
String str2= new String("java2blog");
Three objects will be created here, two in heap memory and one in String constant pool.
You may also like:
    core java interview questions web services interview questions restful web services interview questions Spring interview questions Hibernate interview questions Java Collections interview questions

In this post, we will see how to find all permutations of String in java.
We will use a very simple approach to do it.
Take out first character of String and insert into different places of permutations of remaining String recursively.
Lets say you have String as ABC.
So we take out A from ABC
First character =A and RemainingString = BC 
As we are applying recursion here, we will find permutations of BC.
Take out B from BC.
First character= B and RemainingString = C 
As we are applying recursion here, we will find permutations of C.
When we take out C, our String size becomes 0 and that is our base case here.
First character = C and RemainingString = "" 
We insert C to differences indexes of Permutations  of RemainingString(""), so we get permutation of C as C.
We insert B to different indexes of Permutations of remainingString(C), so we get BC and CB.
C: BC, CB
Now we insert A to different indexes in BC and CB.
BC : ABC , BAC , BCA
CB : ACB, CAB, CBA
so thats how we got all permutations of ABC.
It may look tricky but once you practice the solution, you will be able to understand it better.

Java program to find all Permutations of String in java:

package org.arpit.java2blog;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class PermutationOfStringJava {

 public static void main(String[] args) {

     Set<String> set=permutationOfString("ABC");
     System.out.println("Permutations of String ABC are:");
     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
   String string = (String) iterator.next();
   System.out.println(string);   
  }
 }
 
 public static Set<String> permutationOfString(String str)
 {
  Set<String> permutationSet=new HashSet<String>();
  
  if(str.length()==0)
  {
   permutationSet.add("");
            return permutationSet;
  }
   
  // take out first character of String
  char c=str.charAt(0);
  // Remaining String
  String rem=str.substring(1);
  
  
  Set<String> permutatedSetForRemainingString=permutationOfString(rem);
  for (String permutedString: permutatedSetForRemainingString) {
   for (int j = 0; j <= permutedString.length(); j++) {
    String permutation=insertFirstCharAtDiffPlaces(permutedString,c,j);
    permutationSet.add(permutation);
   }
    
  }
  return permutationSet;
  
 }
 public static String insertFirstCharAtDiffPlaces(String perm,char firstChar,int index)
 {
  // Inserting firstCharacter of orig String at difference places based on index
  return perm.substring(0,index)+firstChar+perm.substring(index);
 }

}
When you run above program, you will get following out:
Permutations of String ABC are:
ACB
ABC
BCA
CBA
CAB
BAC

Core java interview questions play a vital role in java/j2EE interviews. Whether you are fresher or experienced, you are going to face core java interview questions. You can also go through top java interview programs for practicing java programs.
Here I am providing some important core java interview questions with answers.

1. What do you mean by Platform independence of java?

You can write and compile program in one Operating system and run in other operating system.
For example:
You can compile program in Windows and can run it in Unix.

2. What is difference between JVM, JRE and JDK ?

JVM : JVM stands for Java Virtual Machine. It is virtual machine which actually runs the byte code.

JRE : JRE stands for Java Runtime Environment. It provides runtime environment for java code. It has JVM , libraries such as rt.jar and other files.

JDK : JDK stands for Java development kit. It is superset of JRE, it has JRE + compilation and debugging tools(javac and java).

3. What are memory areas allocated in JVM?

Memory areas allocated in JVM are:
  • Heap area
  • Method area
  • JVM language stacks
  • Program counter (PC) register
  • Native method stacks

4. What are some core concepts of OOPS in java ?

Core concepts of OOPs are :
  • Polymorphism
  • Abstraction
  • Encapsulation
  • Inheritance

5. What is Abstraction?

Abstraction is a concept of exposing essential information and hiding implementation details.
For example: 
When you see a car, you know it is running but how it running internally, you may not aware of it.
This is Abstraction. You just expose required details.

6. What is encapsulation?

Encapsulation is process of wrapping data and function into single unit. You can use access modifier for variables, so other classes may not access it directly but it can be accessed only through public methods of the class. You can create class fully encapsulated using private variables.

7. What is Polymorphism in java?

Polymorphism means one name many forms. It is concept by which you can perform same action in different ways. Method overloading and method overriding are example of Polymorphism.

8. What is inheritance in java?

Inheritance allows use of properties and methods of another class (Parent class), so you can reuse all methods and properties.

9. What is constructor in java?

Constructor is block of code which allows you to create instance of the object. It does not have return type.
It has two main points
  • Constructor name should be same as class
  • Constructor should not have any return type else it will be same as method.

10. Can we declare constructor as final?

No, Constructor can not be declared as final. If you do so, you will get compile time error.

11. What is immutable object in java?

Immutable object is object whose state can not be changed once created. You can take String object as example for immutable object.

12. Why String is declared final or immutable in java?

There are various reasons to make String immutable.
  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value
You can refer why String is immutable in java for more details.

13. What are access modifier available in java?

It Specifies accessibility of variables, methods , constructor of class.
There are four access modifier in java
Private : Accessible only to the class.
Default : Accessible in the package.
Protected : Accessible in the packages and its subclasses.
Public : Accessible everywhere

14. What is difference between Abstract class and interface?

Parameter
Abstract class
Interface
Default method Implementation
It can have default method implementation
Interfaces are pure abstraction.It can not have implementation at all but in java 8, you can have default methods in interface.
Implementation
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class
subclasses use implements keyword to implement interfaces and should provide implementation for all the methods declared in the interface
Constructor
Abstract class can have constructor
Interface  can not have constructor
Different from normal java class
Abstract classes are almost same as java classes except you can not instantiate it.
Interfaces are altogether different type
Access Modifier
Abstract class methods can have public ,protected,private and default modifier

Interface methods are by default public. you can not use any other access modifier with it
Main() method
Abstract classes can have main method so we can run it

Interface do not have main method so we can not run it.
Multiple inheritance
Abstract class can extends one other class and can implement one or more interface.

Interface can extends to one or more interfaces only
Speed
It is faster than interface
Interface is somewhat slower as it takes some time to find implemented method in class
Adding new method
If you add new method to abstract class, you can provide default implementation of it. So you don't need to change your current code

If you add new method to interface, you have to change the classes which are implementing that interface

You can refer difference between Abstract class and interface for more details.

15. Can one interface implement another interface in java?

No, One interface can not implement another interface. It can extend it using extends keyword.

16. What is marker interface?

Marker interfaces are interfaces which have no method but it is used to indicate JVM to behave specially when any class implement these interfaces. 
For example : If you implement cloneable interface and then call .clone method of object, it will clone your object. If you do not implement cloneable interface, it will throw cloneNotSupported exception.

17. What is method overloading and method overriding in java?

Method overloading :If two or more methods have same name , but different argument then it is called method overloading.

Method overriding : If subclass is having same method as base class then it is known as method overriding Or in another words, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding

18. Can you override static methods in java?

No, you can not override static methods in java. Static methods belongs to class level not at object level.You can create static method with same name in child class and it won't give you compilation error but it is called method hiding. You won't get overriding behaviour with it.

19. Can you override private methods in java?

No, you can not override private methods in java. Private methods are not visible to child class, hence you can not override it , you can only hide it.

20. Difference between path and classpath in java?

Parameter
Path
classpath
Locate
It allows operating system to locate executable such as javac, java

It allows classloader to locate all .class file used by program
Overriding
You can not override path variable with java setting

You can override classpath by using -cp with java,javac or class-path in manifest file.
Inclusion
You need to include bin folder of jdk (For example jdk1.7.1/bin)
You need to include all the classes which is required by program
Used by
Operating system
java classloaders
You can refer difference between Path and ClassPath in java for more details.

21. What is difference between StringBuffer and StringBuilder in java?

Parameter
StringBuffer
StringBuilder
Thread-safe
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously. 
Performance
It is less performance efficient as it is thread-safe
It is more performance efficient as it is not thread-safe.

22. What are methods you should override when you put an object as key in HashMap?

You need to implement hashcode() and equals() method , if you put key as object in HashMap. You can go through hashcode and equals method in java for more details.

23. Can you explain internal working of HashMap in java?

  • There is an Entry[] array called table which has size 16. 
  • This table stores Entry class's object. HashMap class has a inner class called Entry.This Entry have key value as instance variable. 
Lets see structure of entry class Entry Structure.
static class Entry implements Map.Entry
{
        final K key;
        V value;
        Entry next;
        final int hash;
        ...//More code goes here
} 
Whenever we try to put any key value pair in hashmap, Entry class object is instantiated for key value and that object will be stored in above mentioned Entry[](table). Now you must be wondering, where will above created Entry object get stored(exact position in table). The answer is, hash code is calculated for a key by calling Hashcode() method. This hashcode is used to calculate index for above Entry[] table.
You can read How HashMap works internally in java for more details.

24. Why java uses another hash function internally to calculate hash value apart from hashcode method which you have implemented?

It is due to avoid large number of collisions due to bad hashcode method written by developers.
You can refer hash method of HashMap for more details.

25. What if you don't override hashcode method while putting custom objects as key in HashMap?

As we did not implement hashcode method, each object will have different hashcode(memory address) by default, so even if we have implemented equals method correctly, it won't work as expected.

26. Can you explain internal working of HashSet in java?

HashSet internally uses HashMap to store elements in HashSet. It uses PRESENT as dummy object as value in that HashMap. HashSet uses HashMap to check duplicates in the HashSet.
You can refer How HashSet works internally in java for more details

27. What are differences between HashMap and HashSet in java?

Parameter
HashMap
HashSet
Interface
This is core difference among them.HashMap implements Map interface
HashSet implement Set interface
Method for storing data
It stores data in a form of key->value pair.So it uses put(key,value) method for storing data
It uses add(value) method for storing data
Duplicates
HashMap allows duplicate value but not duplicate keys
HashSet does not allow duplicate values.
Performance
It is faster than hashset as values are stored with unique keys
It is slower than HashMap
HashCode Calculation
In hash map hashcode value is calculated using key object

In this,hashcode is calculated on the basis of value object. Hashcode can be same for two value object so we have to implement equals() method.If equals() method return false then two objects are different.

28. Can you explain internal working of ConcurrentHashMap in java?

ConcurrentHashMap uses concept of Segments to store elements. Each Segment logically contains an HashMap. ConcurrentHashMap does not lock whole object , it just lock part of it i.e. Segment.
Structure of Segment:
 /**
     * Segments are specialized versions of hash tables.  This
     * subclasses from ReentrantLock opportunistically, just to
     * simplify some locking and avoid separate construction.
     */
static final class Segment<k> extends ReentrantLock implements Serializable {
 /**
      * The per-segment table.
*/
        transient volatile HashEntry<k>[] table;
// other methods and variables
} 
It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap. static final class HashEntry {         final K key;         final int hash;         volatile V value;         final HashEntry next; }
You can refer internal working of ConcurrentHashMap in java for more details

29. Do we have lock while getting value from ConcurrentHashMap?

There is no lock while getting values from ConcurrentHashMap.Segments are only for write operation.In case of read operation, it allows full concurrency and provides most recently updated value using volatile variables.

30. How do you sort Collection of custom objects in java?

We need to implement comparable interface to custom object class(Lets say Country) and then implement compareTo(Object o) method which will be used for sorting. It will provides default way of sorting custom objects.
If we want to sort custom object (Lets say country) on different attributes such as name,population etc.We can implement Comparator interface and can be used for sorting.
For more details,you can go through following links:

 31. What are differences between ArrayList and LinkedList in java? 

Parameter
ArrayList
LinkedList
Internal data structure
It uses dynamic array to store elements internally
It uses doubly Linked List to store elements internally
Manipulation
If  We need to insert or delete element in ArrayList, it may take O(n), as it internally uses array and we may have to shift elements in case of insertion or deletion
If  We need to insert or delete element in LinkedList, it will take O(1), as it internally uses doubly LinkedList 
Search
Search is faster in ArrayList as uses array internally which is index based. So here time complexity is O(1)
Search is slower in LinkedList as uses doubly Linked List internally So here time complexity is O(n)
Interfaces
ArrayList implements List interface only, So it can be used as List only
LinkedList implements List,Deque interfaces, so it can be used as List,Stack or Queue

You can refer difference between ArrayList and LinkedList in java for more details.

32. What is Enum in java?

Java Enum is special data type which represents list of constants values. It is a special type of java class. It can contain constant, methods and constructors etc.
You can refer Enum in java for more details.

33. How do you create custom exception in java?

You just need to extends Exception class to create custom exception.
Lets understand this with example.You have list of counties and if You have "USA" in list of country, then you need to throw invalidCountryException(Our custom exception).
Example: 
Create InvalidCountryException.java as below
package org.arpit.java2blog;

public class InvalidCountryException extends Exception{

 InvalidCountryException(String message)
 {
  super(message);
 }
}
Create POJO class called Country.java
package org.arpit.java2blog;

public class Country {
 
 private String name;
 
 Country(String name ){
 this.name = name;
 }
  public String toString() {
   return name;
  }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
  ked
 
}
Lets create CountryCheckMain.java. This class will have main method.
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;

public class CountryCheckMain {

 public static void main(String args[]) {
  List<Country> countries = new ArrayList<Country>();
  Country indiaCountry = new Country("India");
  Country chinaCountry = new Country("China");
  Country nepalCountry = new Country("Nepal");
  Country bhutanCountry = new Country("Bhutan");
  countries.add(indiaCountry);
  countries.add(chinaCountry);
  countries.add(nepalCountry);
  countries.add(bhutanCountry);
  boolean safe;
  try {
   safe = checkListOfCountries(countries);
   if (safe)
    System.out.println("We don't have USA in list of Countries");
   Country USACountry = new Country("USA");
   countries.add(USACountry);
   checkListOfCountries(countries);
  } catch (InvalidCountryException e) {
   e.printStackTrace();
  }

 }

 public static boolean checkListOfCountries(List<Country> countries) throws InvalidCountryException {
  for (int i = 0; i < countries.size(); i++) {
   Country country = countries.get(i);
   if (country.getName().equals("USA")) {
    throw new InvalidCountryException("USA is not allowed");
   }  
  }
  return true;
 }
}
When you run above program, you will get following output:
We don't have USA in list of Country
org.arpit.java2blog.InvalidCountryException: USA is not allowed
 at org.arpit.java2blog.CountryCheckMain.checkListOfCountries(CountryCheckMain.java:37)
 at org.arpit.java2blog.CountryCheckMain.main(CountryCheckMain.java:25)
As you can see, if we have "USA" in list of Countries,we are throwing InvalidCountryException.

34.What is difference between Checked Exception and Unchecked Exception?

Checked Exception: Checked exceptions are those exceptions which are checked at compile. If you do not handle them , you will get compilation error.
For example: IOException
Unchecked Exception : Unchecked exceptions are those exceptions which are not checked at compile time. Java won't complain if you do not handle the exception.
For example: NullPointerException, ArrayIndexOutOfBoundsException 
You can refer difference between checked exception and unchecked exception for more details.

35. Can we have try without catch block in java ?

Yes, we can have try without catch block by using finally block. You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().
You can refer Try with finally block for more details.

36. What are ways to create a thread in java ?

There are two ways to create a thread in java
  • By extending thread class
  • By implementing Runnable interface.

37. What are differences between Sleep and wait in java?

Parameter
wait
sleep
Synchonized
wait should be called from synchronized context i.e. from block or method, If you do not call it using synchronized context, it will throw IllegalMonitorStateException

It need not be called from synchronized block or methods
Calls on
wait method operates on Object and defined in Object class

Sleep method operates on current thread and is in java.lang.Thread
Release of lock
wait release lock of object on which it is called and also other locks if it holds any
Sleep method does not release lock at all
Wake up condition
until call notify() or notifyAll() from Object class
Until time expires or calls interrupt()
static
wait is non static method
sleep is static method
You can refer difference between sleep and wait in java for more details.

38. Define states of thread in java?

There are 5 states of thread in java
New : When you create a thread object and it is not alive yet.
Runnable:  When you call start method of thread, it goes into Runnable state. Whether it will execute immediately or execute after some times , depends on thread scheduler.
Running : When thread is being executed, it goes to running state.
Blocked : When thread waits for some resources or some other thread to complete (due to thread's join), it goes to blocked state.
Dead: When thread's run method returns, thread goes to dead state.

39. Can we call run method directly to start a thread?

No, you can not directly call run method to start a thread. You need to call start method to create a new thread. If you call run method directly , it won't create a new thread and it will be in same stack as main.
You can refer can we call run method directly to start a thread for more details

40. Can we start a thread twice in java?

No, Once you have started a thread, it can not be started again. If you try to start thread again , it will throw IllegalThreadStateException.
You can refer can we start thread twice for more details

41. What is CountDownLatch in java?

As per java docs, CountDownLatch is synchronisation aid that allow one or more threads to wait until set of operations being performed in other threads completes. So in other words, CountDownLatch waits for other threads to complete set of operations.
CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it's interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation.

So count is reduced by 1 whenever latch.countDown() method get called, so if count is n that means count can be used as n threads have to complete some action or some action have to be completed n times.

You can refer CountDownLatch in java with example for more details.

42. What is difference between CountDownLatch and CyclicBarrier?

Parameter
CountDownLatch
CyclicBarrier
Reuse
It can not be reused once count reaches 0
It can be reinitialized once parties reaches to 0, so it can reused
Method 
It calls countDown() method to reduce the counter
It calls await() method to reduce the counter.
Common Event
It can not trigger common event when count reaches 0
It can trigger common event (Runnable) once reaches to a barrier point. Constructor :CyclicBarrier(int parties, Runnable barrierAction)
Constructor
CountDownLatch(int count)
CyclicBarrier(int parties)

43. Why wait, notify and nofiyAll method belong to object class ?

In java, we put locks on shared objects not on thread, so these methods are present in Object class. As every object have mutex(lock), it make sense to put these methods in object class.

44. Can you call wait, notify and notifyAll from non synchronized context?

No, you can not call wait, notify and notifyAll from non synchronized context. If you do so, it will throw IllegalMonitorStateException.

45. What is the difference between creating String as new() and literal?

If you create a String using new operator, it is not interned. It will  create new object in heap memory even if String object already exists with same content.
        String str1=new String("Java2Blog");
        String str2=new String("Java2Blog");
        System.out.println(str1==str2);
It will return false as str1 and str2 will point to different object
If you create a String using assignment operator, it goes to the String constant pool and it is interned. If you create another String with same content, both will reference to same object in String constant pool.
 
String str1="Java2Blog";
String str2="Java2Blog";
System.out.println(str1==str2);
It will return true as str1 and str2 will point to same object in String constant pool.

46. What are Covariant return type in java?

Covariant return type means if subclass overrides any method, return type of this overriding method can be subclass of return type of base class method.
For example:
package org.arpit.java2blog;

public class BaseClass {

 public A m1() {
  System.out.println("In BaseClass method");
  return new A();
 }

 public static void main(String args[])
 {
  BaseClass b=new SubClass();
  b.m1();
 }
}

class SubClass extends BaseClass {
 public B m1() {
  System.out.println("In SubClass method");
  return new B();

 }
}

class A {
}

class B extends A {

}
Above example is perfect example of covariant return type.

47. What is garbage Collection?

Garbage Collection is a process of looking at heap memory and deleting unused object present in heap memory. Garbage Collection frees unused memory. Garbage Collection is done by JVM.

48. What is System.gc()?

This method is used to invoke garbage collection for clean up unreachable object but it is not guaranteed that when you invoke System.gc(), garbage collection will definitely trigger.

49. What is use of finalize() method in object class?

Finalize method get called when object is being collected by Garbage Collector. This method can be used to write clean code before object is collected by Garbage Collector.

50.What is difference between final, finally and finalize in Java?

final : Final is a keyword which is used with class to avoid being extended, with instance variable so they can not reassgined, with methods so that they can not be overridden.
finally : Finally is a keyword used with try, catch and finally blocks. Finally block executes even if there is an exception. It is generally used to do some clean up work.
finalize :  Finalize is a method is used to invoke garbage collection for clean up unreachable object but it is not guaranteed that when you invoke System.gc(), garbage collection will definitely trigger.
You may also like:
    web services interview questions restful web services interview questions Spring interview questions Hibernate interview questions Java Collections interview questions Java String interview questions
 

Java tutorial for beginners Copyright © 2012