How does Map work in Java?

HashMap in Java works on hashing principle. The Map is a data structure which allows us to store object with a key and retrieve same by the same key. Hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method.

 When we call put method,internally  hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal LinkedList. If we dig down the structure we found HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object. When you want to retrieve the object, you call the get() method with  a key object. get() method again generate  key object hash code and eventually ended up with same  bucket location. and returns the value.

Few important things to remember , If you want to use your custom object as a Key of Map

1. It has to be immutable .unless  some one can  change the state.of the object
2. Must override hashcode. As good hashing algorithm, distribution of objects in bucket will be as good
.3. Must override equals method so in  the time of get operation  map  can fetch the key which is identically equal.

public final class CustomKey{
private final String name = "Shamik";
public final String setName(String name)
{
this.name=name;
}
public final String getName(String name){
return name;
}
public int hascode()
{
return name.hascode()*1245/7;
}
public boolean equals(Object obj)
{
if(obj instanceof CustomKey)
{
return this.name.equals(obj.name);
}
return false;
}
}

Here  name is not final so following scenario can occur
CustomKey refKey= new CustomKey();
Map<CustomKey ,String> map = new HashMap<CustomKey,String>();
map.put(refKey,"Shamik");
refKey.setName("Bubun");
map.get(refKey);

It will return null as when equals method invokes it return false. So immutability is must required.

what is servlet collaboration?

Servlet Collaboration means how one servlet can communicate with other. Sometimes servlets are to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods. To perform these operations, each servlet needs to know the other servlet with which it collaborates. Here are several ways to communicate with one another:


1. ServletContext :  In an application, there must be one Servlet context which is shared by all the servlets in this application. It works as a global map .each servlet put  necessary information , which needs to be shared
and other can get that info
  <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.example.ServletTest</servlet-class>
 </servlet>

 <context-param>
   <param-name>name</param-name>
   <param-value>Shamik Mitra</param-value>
 </context-param>




To get this
getServletContext().getInitParameter("email");

Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);

Java Singleton class :

public class Javacontext
{
   private static Javacontext ctx = new Javacontext();
private String name ="Shamik";
private Javacontext()
{
}
public static Javacontext getInstance()
{
return ctx;
}
public String getname()
{
return name;
}
}


Java Properties: Using java properties you can share information

import java.util.*;

public class PropDemo {

   public static void main(String args[]) {
      Properties prop= new Properties();
     Set<String> key;
   
      prop.put("name", "Shamik Mitra");
   

      // Show all states and capitals in hashtable.
      key= prop.keySet(); // get set-view of keys
      Iterator itr = key.iterator();
      while(itr.hasNext()) {
         str = (String) itr.next();
         System.out.println("The key is" +
            str + " name is " + prop.getProperty(str) + ".");
      }
   
   }
}

Can we Overload Main method in java.

Yes you can overload main method but public static void main(String[] args) is entry point in java. JVM always search for this method.
If it is not present in overloaded version ,when you try to run your code that gives run time exception no main method found.


From public static void main(String[] args), you can call other overloaded main function.

Keep in one thing in mind

If some one write

public static void main(String... args)//Varags

That is equivalent public static void main(String[] args) that will gives you compile time error.

Example :
package com.example.main;

public class OverLoadmain {
   
    public static void main(String[] args) {
       
        System.out.println("I am in main ");
       
    }
   
public static void main(int args) {
   
    System.out.println("I am in int");
       
    }


public static void main(String args) {
    System.out.println("I am in String");
}


/*public static void main(String... args) {
    System.out.println("I amn in varags ");
}*/

}

Display trangle in screen using Java.

package com.example.loop.star;

/*
 *
 * This class display triangle as follows
 *
 *         *
 *        * *
 *      * * * *
 *    * * * * * *     
 */

public class DisplayTrangle {
   
    public void triagle_center(int max){//max means maximum star having
        int n=max/2;
       
        /*This loop prints Top star  as  max star is 20 so i first row we have 19 single blanks and one star to complete left hand
         * So n = 20/2 = 10
         *
         * For first row middle point is 11 th position so 19 single blanks one *
         *
         *
         * Row onwards
         *
         * star = row number * 2 if 1st row 2 stars
         * double blank = middle pos - row number;= 10-1=9 double blanks
         *
         * as middle pos is  11.        *
         *
         *
         * *\
         *
         */
       
        for(int m=0;m<((2*n)-1);m++){//for upper star
            System.out.print(" ");
        }
        System.out.println("*");

        for(int j=1;j<=n;j++){
            for(int i=1;i<=n-j; i++){
                System.out.print("  ");
            }
            for(int k=1;k<=2*j;k++){
            System.out.print("* ");
            }

            System.out.println();
        }


    }
   
   
    public static void main(String[] args) {
       
        DisplayTrangle ref = new DisplayTrangle();
        ref.triagle_center(20);
       
    }


}

Is Spring Bean Thread Safe?

Thread safety is a different context . Singleton spring beans has no relation with thread safety. spring container only manages life-cycle of objects and guaranteed that only one object in spring container. so If an Non thread safe object is injected then obviously it is not thread safe. To make it thread safe you have to handle it by coding.

If it is a web-application , Scope("request") can achieve thread-safety  as for each new request it creates a new object or scope("prototype") will do this.(for each  invocation it creates new bean .)

How do you handle error condition while writing stored procedure or accessing stored procedure from java?

When you call a store procedure the store procedure will execute in database server so if there any exception occurs that can be handled in EXCEPTION block in the store proc. If the store procedure it self fails it throws sql exception which can be handled by try/catch block and wrap it to your project specific exception.


example


try {

CallableStatement stmt=con.prepareCall("{call geNamebyId(?)}");

stmt.setInt(1,123);

stmt.execute();

} catch(SQLException e) {

e.printStack();

throw new CustomException(e);//application specific exception

}

What is JCS?

JCS stands for Java Caching System. This is an open source project and released by Apache written in Java.  Like all other caching system JCS  has following features.

1. JCS supports In memory cache.
2. Provide method for add objects in Cache.
3. provide method for retrieve objects from cache
4. provide method for delete objects from cache


apart from this you also can specify how long a object can store in memory.

JCS is used when a object is very costly, say a Composite object which is created by lots of database call and application use it very often. So it is better to put this object in JCS rather than create a new object instance  every time.

So JCS can be used in every application  which has large number of objects which are very costly and use very often.

JCS provide some additional features like
1. Very good memory management
2.Region data separation and configuration
3. Remote synchronization etc.

How to get client machine name and Ip address from Httpservlet?

In HttpServletRequest there are two methods
 a. getRemoteAddr()
 b. getRemoteHost()
 which will provide the necessary information.
 Actually in request header following information is stored.


Ip address of client m/c = request.getRemoteAddr();

Hostname of client =  request.getRemoteHost()

What is difference between include action and include directive in JSP?



Before starting the difference  discussion,  first, we have to understand the JSP life cycle. when a request first comes to a JSP it will translate into servlet then compile and load into web container for further use. Subsequent requests  will serve by this translated servlet.


Let say we have a JSP page called greet.jsp which includes another JSP call  header.jsp. Now it can be included in two ways
 1. by page directive 
 2. by JSP action tag
1. By page directive : syntax is <%@ include file="header.jsp" %>
now when greet.jsp page translated  into a  servlet all the code written in the header.jsp goes to translated servlet's service()(incase of Httpservlet it's //doget() or dopost()) method. so it acts as one servlet which contains two JSP's code ( header.jsp + greet.jsp  ) and ready for serve subsequent requests. Now in mean time suppose  developer change the content of header.jsp, this change will not reflect to translated servlet as it is already compiled and loaded in the web container  . To make this happen you have to restart web container then it will recompile  but some web container smart enough to pick up this changes. so  include page directive is  not a good option for dynamic pages.


2. By JSP action tag: syntax

<jsp:include page="header.jsp">
 Here inclusion is done at request time so it maintains two servlets unlike page directive so it will show updated value each time.  so action tag is the good choice  for dynamic pages.

Benifits of Static methods

Static keywords mean,  methods/variables attached to class, not with objects. So this variables/methods is shared with all objects instances of this class.Following advantages, we can get using static.

1. We can invoke a static method without creating objects. So Utility methods can be static

example

public class DateUtils
{
    public static Date getSystemdate()
{

    return  new Date(System.currenMillsInSecond());
}

  public static Date getPrevousDay()
{
}

//etc


}

.2. If you want to declare a Global value which will share among objects. suppose wants to calculate hit count of a servlet

public class Countservlet extends HttpServlet
{

    private static  int count = 0;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

     count++;
}

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{

   doGet(request,response);
}



}




3. If you want to make a class level synchronization by synchronizing static you can achieve it.


public class Account
{

private static int min_balance=100;

public synchronize void credit(int amount)
{
  min_balance= amount;
}
}


Now no object can change the state of min_balance  as it is class level synchronization.