Thursday, August 11, 2016

Java interview questions for 3 years of experience candidate....

Here i am listing all the interview question, who is having 3 years of experience.

Hibernate Related Question:
  • What is the difference between session.get() and session.load() method in hibernate ?
  • What is the difference between session.update() and session.merge() ?
  • What is first level and second level cache in hibernate ?
  • Can we access a data from data base without using primary key ?
  • How to use composite key in hibernate, how to retrieve and store the data using composite key ?
  • How to communicate with multiple data bases like mysql and oracle from hibernate ?
  • What is the schema in hibernate, How to use it and when to use it ?
  • What is the relationship in hibernate , what are the types and how to declare it ?
  • How to make a pojo as an entity in Hibernate ?
  • What is the difference between eager and lazy loading in hibernate and how to configure it ?
  • What is dirty checking in hibernate ?
  • What optimistic and pessimistic locking in hibernate ?
  • What is the purpose of @Version ? 
  • Dirty checking in hibernate ?
  • What is scalar and how to use it ?
JDBC Related Questions:
  1. How to use jdbc transaction, when it will start the transaction in jdbc code?
  2. What is connection pooling, how to configure and how it will work ?
  3. What are the steps to write a jdbc program ?
  4. What is the difference between statement, prepared statement and callable statement in jdbc ?
  5. How to store image in data base using jdbc, what parameter we have to use to store image ?
  6. How to call a stored procedure in jdbc ?
Spring IOC Related Questions:

  1. What are the IOC container in spring ?
  2. How many types of handler mapping and how to configure,what is the  difference among them ?
  3. Different types of controllers 
  4. Different types of view resolver ?
  5. How many types of injection are there in spring IOC ?Which one is better ?
  6. What is Inversion Of Control ?
  7. What is dependence injection ?
  8. What is the scope and how many types of scope are there in spring IOC ?
  9. What is the difference between singleton and prototype ?
  10. what is the difference between application context and bean factory container in spring IOC ?
  11. What are the interceptor in spring IOC ?
  12. How the IOC container will read the spring configuration file, if we have a customized spring configuration name ?
  13. what is the context listener in web.xml file, how to configure the context listener in web.xml file to read the spring configuration file ?


Spring MVC Related Questions:
  1. What are the annotations, which you used in your project ?
  2. What is @Qualifier annotation in spring mvc ?
  3. What is @Autowired annotation in spring mvc ?
  4. How to enable annotation in  spring mvc ?
  5. How to read the annotation from the controller in spring mvc, what we have to declare in the spring configuration file ?
  6. What is the Spring MVC flow, Explain with diagram ?
  7. what is the difference between @RestController and @Controller in spring MVC ?
  8. What is @Required annotation and at what situation we have to use it in spring MVC ?
  9. What scope do we have to use to get the new object for every request in spring ?
  10. What is Multipart file and what is the use of it ?
  11. what is the Inversion of Control in spring ?
  12. How to schedule a bean in spring ?
  13. How to restrict the service provide to send only the xml format data and how to send only the XML formatted data from spring MVC controller ?
  14. What is @InitBinder in spring mvc ?
  15. What is @Pattern annotation in spring mvc ?
  16. What are the customer property editor in spring mvc ?
J2SE Related Questions:
  1. What is the purpose of  extends and super key words in Generics, When to use it ?
  2. What is the purpose of generics in Java ?
  3. What is OOP'S concepts in Java ?
  4. What is the difference between exception and error, How to handle them using java ?
  5. What is the difference between ArrayList and Linked List ?
  6. What is the difference between HashMap and HashSet ?
  7. What is the difference between Comparable and Comparator ?
  8. What is the difference among String , StringBuilder and StringBuffer ?
  9. What is the life cycle of Thread in java ?
  10. What is the difference between Yield and Sleep method in Thread class ?
  11. What is the difference between Join, Yield and Sleep method in Thread class in java ?
  12. How to sort the elements in ArrayList ?
  13. What is the difference between Abstract class and Interface, Where to use it ?
  14. What are the features on java 1.5,1.6,1.7 and 1.8 ?
  15. What is the HashSet and TreeSet in collections ?
  16. What is String and how to replace a new string value from the  existing string value ?
  17. How to find the file is empty or not using File IO package ?
  18. How to find the file is exist or not using the file IO package ?
  19. How to read the specified line from a file using File IO package ?
  20. What is the difference between File Input Stream and Buffered Input Stream in File IO package ?
  21. What if File Reader and File Writer ?
  22. Which way is the better way to implement multi threading either implementing Runnable  interface or extending Thread class ? 
  23. what is Aggregation and composition in java ?
  24. what is is-a ,has-a relationship in java ? 
Restful Web Service related questions:

  1. How to consume a json object in restful web services ?
  2. How to access restful web services from client application ?
  3. What is query param in restful web services of jersey ?
  4. What is the Path Param in restful web services ?
  5. What is the different between POST and PUT annotation in restful web services ?
SOAP Web Services related questions:


  1. what is schema in SOAP web services ?
  2. What is the top down and bottom up approach ?
  3. Which approach did you followed in your project for SOAP ?
  4. How to access the SOAP web services from client application ?




MySQL related questions :


  1. How to copy the data from one table to other table ?
  2. How to find only the unique records from the table where there are duplicate records is exists?(Distinct)
  3. How to fetch the last 10 records from a table ?
  4. what is sub queries and co related sub queries ?















Monday, July 25, 2016

How to store a default values in a List for a specific size


We can store a default values to the List interfcae implementation classes like ArrayList, LinkedList etc .
The storing a specific default value to the specific size of the array List implementation class is possible, Please check the below code for it.

Storing Integer values 0 as default value to the ArrayList of size 100;
      Integer intArray[] = new Integer[100];
      List al = new ArrayList(Arrays.asList(intArray));
      Collections.fill(al,0);
      System.out.println("ArrayList values are :"+al);
Storing String values "zameer" as default value to the ArrayList of size 100;
      String stArray[] = new String[100];
      List al = new ArrayList(Arrays.asList(stArray));
      Collections.fill(al,"zameer");
      System.out.println("ArrayList values are :"+al);
Please give us your comments on this article.

Monday, July 18, 2016

How to know the data type of the elements from the list of collection objects in java

To know the data types from the list of collection objects in java is by using the below code


public class CheckDataTypes{

      pubic static void main(String[] args){
   
   List list = new ArrayList();
list.add(10);
list.add("hello");
list.add('a');
list.add(34.4);
list.add(22.3f);
for(Object obj:list){
if(obj.getClass().equals(String.class)){
System.out.println(" String type");
}else if(obj.getClass().equals(Integer.class)){
System.out.println("Integer type");
}else if(obj.getClass().equals(Float.class)){
System.out.println("Float type ");
}else if(obj.getClass().equals(Double.class)){
System.out.println("Double type ");
}else if(obj.getClass().equals(Character.class)){
System.out.println("Char Type");
}
}
      }//Main method closed

}// class ended



One more way is : 


public class DataType {
   public static void main(String args[]){
     
  List list = new ArrayList();
list.add(10);
list.add("hello");
list.add('a');
list.add(34.4);
list.add(22.3f);
for(Object obj:list){
if(obj instanceof String){
System.out.println(" String type");
}else if(obj instanceof Integer){
System.out.println("Integer type");
}else if(obj instanceof  Float){
System.out.println("Float type ");
}else if(obj instanceof  Double){
System.out.println("Double type ");
}else if(obj instanceof Character){
System.out.println("Char Type");
}
    }//for each loop closed
   }//main method closed
}//Class is closed

Is this variable declaration is valid?

       
In the below different variable declaration is valid.

Class Test{


  1.         int a=0.0;  
  2. Integer b=23.4;
  3. String s='d';
  4. char c="sample";
  5. char ch[]="simple data";
  6. float f=34.5;
  7. double d=f;
  8. long l=d;

}

1.Compilation error. Error : Type mismatch: cannot convert from double to int
2.Compilation error: Error:  Type mismatch: cannot convert from double to Integer
3.Compilation error: Error:  Type mismatch: cannot convert from char to String
4.Compilation error: Error:  Type mismatch: cannot convert from String to char
5.Compilation error: Error:  Type mismatch: cannot convert from String to Char Array
6.Compilation error: Error:  Type mismatch: cannot convert from double to float
8.Compilation error: Error:  Type mismatch: cannot convert from double to long

Saturday, July 9, 2016

What is request dispatcher and how many ways we can create an dispatcher object

Request Dispatcher :


Request Dispatcher is an interface which is having two methods forward(request, response) and include(request,response).

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

Simple explanation of request dispatcher is to forward control(request) to the next resource (like jsp,servlet or html) which has to do the processing of the request  and it will return the result to the end user or it can return the processed request to the calling function to fulfill the remaining processing of the request then the calling function will return the result to the end user.

We can create Request dispatcher in two ways

ServletContext context = getServletContext();
                 RequestDispatcher dispatcher = context.getRequestDispatcher("/processing.jsp");
                 dispatcher.forward(request,response);
RequestDispatcher requestDispatcher; 
requestDispatcher = request.getRequestDispatcher("/thankYou.jsp");   
requestDispatcher.forward(request, response); 
requestDispatcher.include(request,response);

Monday, June 27, 2016

Java Collections class methods example



package com.corejava.collection;
import java.util.*;
class CollectionsDemo
{
public static void main(String[] args)
{
  List list = new ArrayList();
  list.add(20);
  list.add(2);
  list.add(34);
  list.add(1);
  list.add(5);
  list.add(45);

  //Using Collections class method, we can do many operation, lets do with one by one

  //As we know , list can hold the insertion order, if you want to reverse the insertion order,
  //Use the Collections.reverse(list) method to reverse the elements from list

  Collections.reverse(list);

  //If you want to sort the elements accoridng the asscending order then we can use

  Collections.sort(list);
  //If you want to find the Maximum or Minimum elements from the list then

  Collections.max(list);
  Collections.min(list);

  //If you want to synchronize the list, which is not a synchronized then

  Collections.synchronizedCollection(list);
  // Or
  Collections.synchronizedList(list);

  Collections.shuffle(list);
  System.out.println(" List is :"+list.toString());

  HashMap map = new HashMap();
  map.put("one", 1);
  map.put("two", 2);
  map.put("three", 3);
  //for synchronizing the map using the collections class
  Collections.synchronizedMap(map);
 
 Set  set = new HashSet();
 set.add(10);
 set.add(2);
 set.add(23);
 set.add(44);
 set.add(1);
 Collections.max(set);
 Collections.min(set);
 Collections.synchronizedSet(set);//or
 Collections.synchronizedCollection(set);  
     }
}

Friday, June 24, 2016

Spring Bean Scoops

Spring support 5 types of bean scoops


  1. Singleton : singleton scope will return same object reference if you call multiple time to the bean from the IOC Container.
  2. Prototype  : It will return new object reference of the bean for every request we do with IOC  Container.
  3. Request : Return single bean instance per HTTP request.
  4. Session  : Return single bean instance per HTTP Session
  5. Global session : Returns single bean instance per HTTP Global Session.
  6. Application(V4.0): 
 Example of Singleton Scope: 
import com.javacontainer.service.customer;
public class CustomerService 
{
String message;
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

Bean Configuration in Configuration xml file


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-2.5.xsd">

       
            class="com.javacontainer.service.customer.CustomerService" />
Calling the Bean
package com.javacontainer.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javacontainer.service.customer.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
    ApplicationContext context = 
    new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

    CustomerService custA = (CustomerService)context.getBean("customerService");
    custA.setMessage("Message by custA");
    System.out.println("Message : " + custA.getMessage());
   
    //retrieve it again
    CustomerService custB = (CustomerService)context.getBean("customerService");
    System.out.println("Message : " + custB.getMessage());
    }
}

OutPut:

 Message : Message by custA
 Message : Message by custA


Example of Prototype Scope of Bean Configuration




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-2.5.xsd">

       
            class="com.javacontainer.service.customer.CustomerService"  scope="prototype"/>

OutPut

Message : Message by custA
Message : null

Bean Scope Configuration using Annotation :

package com.javacontainer.service.customer.CustomerService;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class CustomerService 
{
String message;
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

To Read the annotation by the IOC Container we need to configure the element inside the spring configuration file :


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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

       





Wednesday, June 22, 2016

How to call a finalize method with different ways


To  call a finalize method from a code , we have different ways.

There are different ways to call a Garbage Collector to remove the non reference object, but we can't say exact what time will it remove the object from the memory.
Below are the following few ways to call the garbage collector.

1. System.gc():

  Example :  
                     Class Test{
                           public static void main(String[] args{
                                 Test t = new Test();
                                System.gc();
                           }
                       }

2. Object reference of your class dot finalize() method
   
      Example :  
                     Class Test{

                           public static void main(String[] args{
                           
                                 Test t = new Test();
                                  t.finalize();//Here we are calling garbage collector by using the finalize method
                           }
                       }
3. System.runFinalization():
 
This will tell the Garbage Collector to give me preference to remove  the objects
Example:

       public static void main(String args[]){
Test t=new Test();
 t.setName("ganesh");
System.runFinalization();
 System.out.println("Name is :"+t.getName());

}

Monday, June 20, 2016

Translating JSP scriptlet code to servlet service life cycle method

Scriptlets are nothing but java code enclosed within <% and %> tags. JSP container moves the statements enclosed in it to _jspService()method while generating servlet from JSP. The reason of copying this code to service method is: For each client’s request the _jspService() method gets invoked, hence the code inside it executes for every request made by client.
Syntax of Scriptlet:
[code language=”java”]<% Executable java code%>[/code]

JSP to Servlet transition for Scriptlet –

As I stated in my previous tutorials that JSP doesn’t get executed directly, it first gets converted into a Servlet and then Servlet execution happens as normal. Also, I explained in first para that while translation from JSP to servlet, the java code is copied from scriptlet to _jspService() method. Lets see how that happens.
Sample JSP code:
[code language=”html”]

Sample JSP


<% myMethod();%>
[/code]
Note: Semicolon at the end of scriptlet.
Corresponding translated Servlet code for above JSP code:
[code language=”java”]
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("

Sample JSP

");
myMethod();
}[/code]

Friday, June 17, 2016

How to call a store procedure from hibernate?

Creating Stored Procedure in MYSQL

mysql> DELIMITER //
mysql> create procedure usp_totalEmployeeByDeparment(IN id INT)
    -> begin
    -> select count(*) as total from employee where dept_id = id;
    -> end//

Calling Stored Procedure from mysql command line

MYSQL >  CALL usp_totalEmployeeByDepartment(100);



How to call Stored Procedure from hibernate native sql and named query 


Native SQL
Query query = session.createSQLQuery(
"CALL usp_totalEmployeeByDeparment(:id)").addEntity(Employee.class).setParameter("id", 7277);

List result = query.list();
for(int i=0; i Employee emp= (Employee)result.get(i);
System.out.println(emp.getDepartment());
}

Named Query

Query query = session.getNamedQuery("usp_totalEmployeeByDeparment").setParameter("id", 7277);
List result = query.list();
for(int i=0; i Employee emp= (Employee )result.get(i);
System.out.println(emp.getDepartment());
}

Saturday, June 11, 2016

What is the difference among session.evict(),session.clear() and session.close()?

In Hibernate we have two kinds of cache first level and second level, for the first level cache will be associated with the session object of hibernate.where we are going to store the retrieved object from the data base for further use in the application.
For some scenario we have to remove those persisted object from the session object, to do that we have to use the following session methods.

  1. session.evict()
  2. session.clear()
  3. session.close()
Session.evict() :
  • Session.evict() method is used to remove the single object from the session.
           Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove only one  student object obj1 from session cache, we have to use the session method evict()

          session.evict(obj1); //Here we are removed obj1 object from session object
session.clear()
  • session.clear() method is used to remove all the persisted objects from the session first level cache.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove both   student objects obj1 and obj2 from session cache, we have to use the session method clear().

          session.clear(); //Here we are removed obj1  and obj2 object from session object

session.close()
  • session.close() method is used to close the session object associated with the session factory, which is no more exits to perform the data base operation using the persistent class and first level cache also automatically not available.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache. If you  close the session object  both   student objects obj1 and obj2 from session cache will be deleted along with the session object, we have to use the session method close().

          session.close(); //Here we are closing session object, simultaneously both obj1 and obj2 also removed from the session.




           

Friday, June 10, 2016

Difference between Hibernate SessionFactory and Session interfaces

Session Factory


  • Session Factory is a heavy weight object, because it need to read the mapping file, configuration file and other configuration file to create one session factory object.that why we call it as heavy weight object.
  • Session Factory is a thread safe object, no two threads access simultaneously  and session factory object will be one per application.
  • Session Factory is a factory which is going to create a no of session objects which are light weight.
  • Session Factory is responsible for creating and  managing the session objects.
  • Session Factory object will be created one per application and it will be 
                SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Session

  • Session is a light weight object and not thread safe. i.e it can access multiple thread simultaneously.
  • Session object is used to interact with the data base to perform CRUD(Create, Read, Update, Delete) Operations.
  • Session is one per request and it will hold the data base connection when  we call the CRUD operation, we call it as lazy initializing. 
           SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();
                                    Session session=sessionFactory.openSession();

Avoiding Too Many connection of Session in hibernate using ThreadLocal class to get the current session without creating multiple times

import java.lang.ThreadLocal;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.HibernateException;

public class HibernateUtil
{
    public static final ThreadLocal local = new ThreadLocal();

    // Creating Session Factory Object
    SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();

    // To get the current Session object from Session Factory object
    public static Session currentSession() throws HibernateException
    {
       Session session = (Session) local.get();

       //open a new session if this thread has no active session
       if(session == null)
       {
          session = sessionFactory.openSession();
          local.set(session);
       }

       return session;
    }
}

Wednesday, March 23, 2016

Creating Primary and foreign key relationship between two tables in mysql

Primary and foreign key relationship between two tables

1.First we need to create a Primary key field table
CREATE TABLE Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    discount DOUBLE,
    type VARCHAR(255),
    price DOUBLE
) ENGINE=INNODB;

2.After creating primary field table, we have to create second table 

CREATE TABLE Normal_Sale(
    sale_id CHAR(40),
    PRIMARY KEY(sale_id),
    FOREIGN KEY (sale_id) REFERENCES Sale(sale_id)
) ENGINE=INNODB;

Sunday, March 13, 2016

XML Request and Response from Spring restful web services using POJO

How to call a spring restful web service to consume and produce XML as request and response using a Pojo class.

1.I have a Pojo class called as ItemDTO,which looks like this to support xml as input to the service

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ITEM_STOCK")
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemDTO implements Serializable {


private static final long serialVersionUID = 4520881241472376875L;

@XmlElement
private String item_name;
@XmlElement
private String item_desl;
@XmlElement
private int item_count;
   
       //Setters and Getters of the variables above.
}

2.Spring rest Controller

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ims.xml.DTO.ItemDTO;


@Controller
@RequestMapping(value="ims")
public class InventoryHomeController {

@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)

public @ResponseBody ItemDTO home(Locale locale, Model model) {

model.addAttribute("serverTime", formattedDate);
ItemDTO i = new ItemDTO("renolds", "ballpointpen", 10);

return i;
}
}

OUT PUT IS:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>

<ITEM_STOCK>

<item_name>renolds</item_name>

<item_desl>ballpointpen</item_desl>

<item_count>10</item_count>

</ITEM_STOCK>