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

Sunday, November 23, 2014

Java Objects to XML and XML to Java Objects - XStream

Java Objects to XML and XML to Java Objects with XStream

 

 import java.io.File; 
 import java.io.FileReader; 
 import java.io.FileWriter; 
 import java.io.IOException; 
 import java.util.Iterator; 
 import java.util.List; 
 import com.thoughtworks.xstream.XStream; 

 public final class XStreamTranslator { 
     private XStream xstream = null; 
     private XStreamTranslator(){ 
         xstream = new XStream(); 
         xstream.ignoreUnknownElements(); 
} 
     /** 
      * Convert a any given Object to a XML String 
      * @param object 
      * @return 
      */ 
     public String toXMLString(Object object) { 
         return xstream.toXML(object);  
     } 
     /** 
      * Convert given XML to an Object 
      * @param xml 
      * @return 
      */ 
     public Object toObject(String xml) { 
         return (Object) xstream.fromXML(xml); 
     } 
     /** 
      * return this class instance 
      * @return 
      */ 
     public static XStreamTranslator getInstance(){ 
         return new XStreamTranslator(); 
     } 
     /** 
      * convert to Object from given File  
      * @param xmlFile 
      * @return 
      * @throws IOException  
      */ 
     public Object toObject(File xmlFile) throws IOException { 
         return xstream.fromXML(new FileReader(xmlFile)); 
     } 
     /** 
      * create XML file from the given object with custom file name 
      * @param fileName  
      * @param file 
      * @throws IOException  
      */ 
     public void toXMLFile(Object objTobeXMLTranslated, String fileName ) throws IOException { 
         FileWriter writer = new FileWriter(fileName); 
         xstream.toXML(objTobeXMLTranslated, writer); 
         writer.close(); 
     } 
     public void toXMLFile(Object objTobeXMLTranslated, String fileName, List omitFieldsRegXList) throws IOException { 
         xstreamInitializeSettings(objTobeXMLTranslated, omitFieldsRegXList); 
         toXMLFile(objTobeXMLTranslated, fileName);     
     }     
     /** 
      * @ 
      * @param objTobeXMLTranslated 
      */ 
     public void xstreamInitializeSettings(Object objTobeXMLTranslated, List omitFieldsRegXList) { 
         if(omitFieldsRegXList != null && omitFieldsRegXList.size() > 0){ 
             Iterator itr = omitFieldsRegXList.iterator(); 
             while(itr.hasNext()){ 
                 String omitEx = itr.next(); 
                 xstream.omitField(objTobeXMLTranslated.getClass(), omitEx); 
             } 
         }  
     } 
     /** 
      * create XML file from the given object, file name is generated automatically (class name) 
      * @param objTobeXMLTranslated 
      * @throws IOException 
      * @throws XStreamTranslateException  
      */ 
     public void toXMLFile(Object objTobeXMLTranslated) throws IOException { 
         toXMLFile(objTobeXMLTranslated,objTobeXMLTranslated.getClass().getName()+".xml"); 
     }

 

  public static Document readFromXml(String input) throws InvalidDataException {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(IOUtils.toInputStream(input));
        } catch (Exception e) {
            throw new
Exception("Exception occured while converting input String into document", e);
        }
    }  

// Intialize Java object and create XML

 public static String initializeAndWriteToXml(Object objectToWrite) {
        final XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(final MapperWrapper next) {
                return new HibernateMapper(next);
            }
        };
        xstream.registerConverter(new HibernateProxyConverter());
        xstream.registerConverter(new HibernatePersistentCollectionConverter(xstream.getMapper()));
        xstream.registerConverter(new HibernatePersistentMapConverter(xstream.getMapper()));
        xstream.registerConverter(new HibernatePersistentSortedMapConverter(xstream.getMapper()));
        xstream.registerConverter(new HibernatePersistentSortedSetConverter(xstream.getMapper()));

        return xstream.toXML(objectToWrite);
    }

// Return class object

  public static <T> T readFromXml(String xmlContent, Class<T> targetObjectClass) {
        return targetObjectClass.cast(xstream.fromXML(xmlContent));
    }

 }

Thursday, November 20, 2014

JSON to HashMap - Parsing JSON String

Recursivey Parsing JSON String to HashMap


Json String can contain JsonArray, JsonObject etc.

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

public class TestJson{

    public static void main(String args[]) throws Exception {
        JSONObject jsonObject = new JSONObject(
                "{\"A\":\"M1\",\"Data\":[ {\"B\":[{ \"B1\":\"111\",\"B2\":\"Warning \"},{ \"B1\":\"222\",\"B2\":\"Warning \"}],\"C\":[{\"c1\":\"IL2\",\"c2\":\"[0.750183,0.00933380975964486]\"},{\"c1\":\"IL1b\",\"c2\":\"[0.750183,-1.5216938335421]\"}]}]}");
        System.out.println(getMap(jsonObject));
    }

    private static Map getMap(JSONObject object) {
        Map<String, Object> map = new HashMap<String, Object>();

        Object jsonObject = null;
        String key = null;
        Object value = null;

        try {
            Iterator<String> keys = object.keys();
            while (keys.hasNext()) {

                key = null;
                value = null;

                key = keys.next();

                if (null != key && !object.isNull(key)) {
                    value = object.get(key);
                }

                if (value instanceof JSONObject) {
                    map.put(key, getMap((JSONObject) value));
                    continue;
                }

                if (value instanceof JSONArray) {
                    JSONArray array = ((JSONArray) value);
                    List list = new ArrayList();
                    for (int i = 0 ; i < array.length() ; i++) {
                        jsonObject = array.get(i);
                        if (jsonObject instanceof JSONObject) {
                            list.add(getMap((JSONObject) jsonObject));
                        } else {
                            list.add(jsonObject);
                        }
                    }
                    map.put(key, list);
                    continue;
                }

                map.put(key, value);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return map;
    }
}


How to avoid extra POJO's / Classes

package com.package;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

public class Test{

    public static void main(String[] args) {

        String json = "[{\"givenName\": \"Adrienne H.\",\"surname\": \"Kovacs\"},{\"givenName\": \"Philip\",\"surname\": \"Moons\"}]";
        ObjectMapper mapper = new ObjectMapper();
        List<Author> list = new ArrayList<Author>();
        try {
            list = mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, Author.class));
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(list);
    }
}
 
So here i do not need to map List<Author> inside any other class.

Tuesday, November 18, 2014

Java Design Pattern - Factory pattern

Background information

This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations. This not only makes our architecture more flexible but also less fragile.
A picture is worth thousand words. Lets see how a factory implementation will look like.

Above class diagram depicts a common scenario using example of car factory which is able to build 3 types of cars i.e. small, sedan and luxury. Building a car requires many steps from allocating accessories to final makeup. These steps can be written in programming as methods and should be called while creating an instance of a specific car type.
If we are unfortunate then we will create instances of car types (e.g. SmallCar) in our application classes and thus we will expose the car building logic to outside world and this is certainly not good. It also prevents us in making changes to car making process because code in not centralized, and making changes in all composing classes seems not feasible.

Implementation

So far we have seen the classes need to be designed for making a CarFactory. Lets hit the keyboard now and start composing our classes.
CarType.java will hold the types of car and will provide car types to all other classes

package designPatterns.factory;

public enum CarType {
    SMALL, SEDAN, LUXURY
}

Car.java is parent class of all car instances and it will also contain the common logic applicable in car making of all types.

package designPatterns.factory;

public abstract class Car {

    public Car(CarType model) {
        this.model = model;
        arrangeParts();
    }

    private void arrangeParts() {
        // Do one time processing here
    }

    // Do subclass level processing in this method
    protected abstract void construct();

    private CarType model = null;

    public CarType getModel() {
        return model;
    }

    public void setModel(CarType model) {
        this.model = model;
    }
}

 LuxuryCar.java is concrete implementation of car type LUXURY

package designPatterns.factory;

public class LuxuryCar extends Car {

    LuxuryCar() {
        super(CarType.LUXURY);
        construct();
    }

    @Override
    protected void construct() {
        System.out.println("Building luxury car");
        // add accessories
    }
}

SmallCar.java is concrete implementation of car type SMALL

package designPatterns.factory;

public class SmallCar extends Car {

    SmallCar() {
        super(CarType.SMALL);
        construct();
    }

    @Override
    protected void construct() {
        System.out.println("Building small car");
        // add accessories
    }
}

SedanCar.java is concrete implementation of car type SEDAN

package designPatterns.factory;

public class SedanCar extends Car {

    SedanCar() {
        super(CarType.SEDAN);
        construct();
    }

    @Override
    protected void construct() {
        System.out.println("Building sedan car");
        // add accessories
    }
}

CarFactory.java is our main class implemented using factory pattern. It instantiates a car instance only after determining its type.

package designPatterns.factory;

public class CarFactory {
    public static Car buildCar(CarType model) {
        Car car = null;
        switch (model) {
        case SMALL:
            car = new SmallCar();
            break;

        case SEDAN:
            car = new SedanCar();
            break;

        case LUXURY:
            car = new LuxuryCar();
            break;

        default:
            // throw some exception
            break;
        }
        return car;
    }
}

 In TestFactoryPattern.java, we will test our factory code. Lets run this class.

package designPatterns.factory;

public class TestFactoryPattern {
    public static void main(String[] args) {
        System.out.println(CarFactory.buildCar(CarType.SMALL));
        System.out.println(CarFactory.buildCar(CarType.SEDAN));
        System.out.println(CarFactory.buildCar(CarType.LUXURY));
    }
}

Output:

Building small car
designPatterns.factory.SmallCar@7c230be4
Building sedan car
designPatterns.factory.SedanCar@60e1e567
Building luxury car
designPatterns.factory.LuxuryCar@e9bfee2

As you can see, factory is able to return any type of car instance it is requested for. It will help us in making any kind of changes in car making process without even touching the composing classes i.e. classes using CarFactory.

Advantages of factory pattern

By now, you should be able to count the main advantages of using factory pattern. Lets note down:
  • The creation of an object precludes its reuse without significant duplication of code.
  • The creation of an object requires access to information or resources that should not be contained within the composing class.
  • The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.

Monday, August 18, 2014

Hibernate’s and LazyInitializationExceptions

For many years LazyInitializationExceptions have become most frustrating point of Hibernate. This exception occurs when you try to access an un-initialised lazy association of a detached entity.
Entities become detached in three different ways;
  • session close
  • session clear
  • session evict
You have to be sure that any lazy attributes you will access be initialised before those three cases happen. Otherwise you will come up with the infamous Lazy exception.
So what are the ways to get rid of that Lazy exception? There are several ways available in Hibernate and employed among the community;
  • You can invoke Hibernate.initialize(proxy) on each lazy attribute before their owning entity becomes detached.
  • You have to access their specific properties such as ids before detachment such as x.getLazySet().size() or x.getLazyManyToOneAssoc().getId().
  • For web applications you can also employ OpenSessionInViewFilter which keeps session open until the end of view render process so that entities wont become detached before those lazy attributes accessed.
  • You can also reattach detached entities before accessing their lazy attributes using session merge or lock operations.
With Hibernate 4.1.6 a new feature is introduced to handle those lazy association problems. When you enable hibernate.enable_lazy_load_no_trans property in hibernate.properties or in hibernate.cfg.xml, you will have no LazyInitializationException any more. It works for any sort of lazy associations not only many sided (1:M, N:M) but also one sided (1:1,:M:1) as well.
So what does this property do? It simply signals Hibernate that it should open a new session if session which is set inside current un-initialised proxy is closed. You should be aware that if you have any other open session which is also used to manage current transaction, this newly opened session will be different and it may not participate into the current transaction unless it is JTA. Because of this TX side effect you should be careful against possible side effects in your system.
Another important point is that this feature only works for proxies whose sessions are closed or their owning entity is evicted from the session. If the entity become detached with session clear then you will still have the lazy problem. According to code comments in Hibernate’s AbstractPersistentCollection class, Hibernate team aims to handle session clear in the next major release.

Friday, August 15, 2014

Flushing Hibernate

Flushing Hibernate

Today I am going to write about Hibernate flushing. Do not worry, I am not going to flush Hibernate to the toilet. I will write about the way, how Hibernate propagates changes to the database.
When you are modifying data using Hibernate, you have to keep in mind that Hibernate uses so called write-behind. It means that Hibernate propagates changes to the database as late as possible. By default this propagation (flushing) happens at the following times
  • when transaction is committed
  • before query is executed
  • when flush() method is called explicitly
Usually such behavior is a good thing. It enables Hibernate to optimize data modifications and allows grouping many changes to one big batch update. But sometimes you can encounter some interesting issues. Lets show it on some example. Lets have following entity class:



01 @Entity
02 public class Client  {
03   
04   @Id @GeneratedValue(strategy=GenerationType.AUTO)
05   private Long id;
06
07   @Column(unique=true,nullable=false)
08   private String personalNumber;
09   
10   @Column
11   private String name;
12   
13   .
13   .
13   .
14 }
We see that a client has id which is used internally as an identifier. Moreover a client has a personal number which we are using as a business key. Then he has some other attributes as name. Notice that the personal number is obligatory and it has to be unique.

01     Client client = new Client(PERSONAL_NUM);
02     LOG.debug("Creating first client");
03     clientDao.createClient(client);
04     
05     LOG.debug("Changing first client");
06     client.setName("Carl von Bahnhof");
07     
08     LOG.debug("Deleting first client");
09     clientDao.deleteClient(client.getId());
10     
11     LOG.debug("Trying to load first client");
12     assertNull(clientDao.loadClientWithPersonalNumberOrReturnNull(PERSONAL_NUM));
13     
14     LOG.debug("Creating second client");
15     clientDao.createClient(new Client(PERSONAL_NUM));

When it is executed on HSQLDB we get following output (we see my logging messages mixed with Hibernate SQL output).

Creating first client
insert into Client (name, personalNumber, id) values (?, ?, ?)
call identity()
Changing first client
Deleting first client
Trying to load first client
delete from Client where id=?
select client0_.id as id2_, client0_.name as name2_, client0_.personalNumber as personal3_2_ from Client client0_ where client0_.personalNumber=?
Creating second client
insert into Client (name, personalNumber, id) values (?, ?, ?)
call identity()
We see that inserts are called at once. They are not postponed until flush. In this case, Hibernate has to call insert at once because it has to get the client id from the database. (remember all non-transient entities have to have id) So inserts can not wait until flush, they have to be executed directly. In order to make our example more clear, we can change id generation strategy to sequence.



01 @Entity
02 public class Client  {
03   
04   @Id @GeneratedValue(strategy=GenerationType.SEQUENCE)
05   private Long id;
06
07   @Column(unique=true,nullable=false)
08   private String personalNumber;
09   
10   @Column
11   private String name;
12   
13   .
14   .
15   .
16 }
To get the client id, insert is not needed any more. It can be postponed until flush and we get following output
Creating first client
select next value for hibernate_sequence from dual_hibernate_sequence
Changing first client
Deleting first client
Trying to load first client
insert into Client (name, personalNumber, id) values (?, ?, ?)
delete from Client where id=?
select client0_.id as id2_, client0_.name as name2_, client0_.personalNumber as personal3_2_ from Client client0_ where client0_.personalNumber=?
Creating second client
insert into Client (name, personalNumber, id) values (?, ?, ?)
As you can see creation of the first client and his deletion is realized just before the select statement. Changes have to be propagated to the DB so the select statement has access to changed data. You can notice, that there is no update, change of the name was already included into the insert statement. So far so good. Where is the problem? Lets comment out the query (You do not have to comment it out, in the real world it can be bypassed by the second-level cache).



01     Client client = new Client(PERSONAL_NUM);
02     LOG.debug("Creating first client");
03     clientDao.createClient(client);
04     
05     LOG.debug("Changing first client");
06     client.setName("Carl von Bahnhof");
07     
08     LOG.debug("Deleting first client");
09     clientDao.deleteClient(client.getId());
10     
11     //LOG.debug("Trying to load first client");
12     //assertNull(clientDao.loadClientWithPersonalNumberOrReturnNull(PERSONAL_NUM));
13     
14     LOG.debug("Creating second client");
15     clientDao.createClient(new Client(PERSONAL_NUM));
We get following output
Creating first client
select next value for hibernate_sequence from dual_hibernate_sequence
Changing first client
Deleting first client
Creating second client
insert into Client (name, personalNumber, id) values (?, ?, ?)
insert into Client (name, personalNumber, id) values (?, ?, ?)
SQL Error: 0, SQLState: null
failed batch
Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:438)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:662)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:632)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:346)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:199)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:340)
at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:351)
at org.springframework.test.context.junit4.SpringMethodRoadie.runBeforesThenTestThenAfters(SpringMethodRoadie.java:262)
at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:234)
at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:204)
at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:146)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:151)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.sql.BatchUpdateException: failed batch
at org.hsqldb.jdbc.jdbcStatement.executeBatch(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeBatch(Unknown Source)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
... 31 more
Wow. It looks like Hibernate is trying to insert both clients with the same personal number without deleting the first one. Lets try to remove uniqueness condition from the client and take a look at the output:
Creating first client
select next value for hibernate_sequence from dual_hibernate_sequence
Changing first client
Deleting first client
Creating second client
insert into Client (name, personalNumber, id) values (?, ?, ?)
insert into Client (name, personalNumber, id) values (?, ?, ?)
delete from Client where id=?
Yes, Hibernate changed order of the commands! Without the unique constraint it does not matter, final result is the same. But with the constraint enabled, we can not use our code any more. Is it a bug? No, it is a feature. If you dig deep into the Hibernate source code, you will find following comment
Execute all SQL and second-level cache updates, in a
special order so that foreign-key constraints cannot
be violated:
  1. Inserts, in the order they were performed
  2. Updates
  3. Deletion of collection elements
  4. Insertion of collection elements
  5. Deletes, in the order they were performed
And that is exactly our case. When flushing, Hibernate executes all inserts before delete statements.
So if we need to run our example, we have to force Hibernate to flush the delete before the second insert. The best way is to call entityManager.flush() explicitly just after the delete.
To reiterate, Hibernate is using write-behind. All data manipulating statements are executed as late as possible. One exception are insert statements. Sometimes Hibernate needs to call insert in order to get the ID of the entity. The important point is, that order of the commands can be changed by Hibernate. Usually it does not matter, since transactions are atomic. But sometimes we can encounter interesting issues. Especially when using database constraints.

Wednesday, June 25, 2014

Java/J2EE (Core Java, Spring, HIbernate, JSP, Ajax) Interview Questions

Interview Question
Core Java
Basics
  1. What do you understand by JVM.
  2. Relate JDK and JRE and its uses.
  3. How to generate class file from java file
javac Test.java

  1. If i create java file in windows and compiles in windows and run in linux .What I have to do to make it compatible.
  2. What are different ways of instantiating a class.
MyObject object = new MyObject();

            MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

           MyObject anotherObject = new MyObject();
           MyObject object = anotherObject.clone();

           ObjectInputStream inStream = new ObjectInputStream(anInputStream );
           MyObject object = (MyObject) inStream.readObject();





  1. Describe public, private and protected modifiers.
  2. Say I have Test class with main method.
Public class Tests {
public static void main(String[] args) {
testMethod();
}


private static void testMethod() {
testMethod();
}
}

Stack overflow error

  1. Interface vs abstract class
  2. Method overloading and overriding, which polymorphism works at runtime and compile time, give examples.
  3. Autoboxing and unboxing.

Exception handling
  1. What is hierarchy
  2. Try, catch and finally. Use of catch, finally
  3. What to do if I do not want to execute finally
  4. If I want to write my own exception class
  5. If I write return statement in try. Below question. Output..?? ab

public class HelloWorld{
public static void main(String []args){
String s= "";
s = getMsg();
System.out.println(s);
}
private static String getMsg(){
String a = "a";
try{
a=a+"b";
return a;
}catch(Exception e){
}finally{
a=a+"c";
System.out.println(a);
}
return "fi";
}
}
Generic
  1. What are generics and when and why were they introduced.
  2. When does generics come into play, compile time or runtime or both.
  3. What happens to generic code when you compile a class.
  4. Design a generic class which can except any type employee id.

Log4J
  1. Levels and there logging hierarchy.
Serialization
  1. What is serialization and why do we need serialization.
  2. How can I achieve serialization
  3. What are the methods present in serializable interface.
  4. What is the use of serial version id.
  5. What I will do if I do not want to serialize a particular attribute of the object.
  6. What is externalization.

Collections
  1. What are different types of collections used.
  2. Diff between hashmap and hashtable.
  3. What is concurrent hashmap
  4. How hashing and equals method works
  5. Hashset internal working – don’t add equals and hash method , then output
  6. Treeset add objects of simple class – exception occurs
  7. Comparator and comparable.
  8. Describe about collection and collections.
  9. Iterator and list Iterator
  10. Concurrent modification exception example.
  11. FailFastVSFailSafe
Threads
  1. How to implement threads
  2. Diff between booth implementation
  3. Static vs instance method calling.
//Creating new instance for every thread access.
 ExtendsThread tc1 = new ExtendsThread();

//Multiple threads share the same object.
 ImplementsRunnable rc = new ImplementsRunnable();

  1. Idea about fork joins
Java Design pattern - singleton
JSP
  1. JSP lifecycle
JSP Page Translation:
jSP Page Compilation:
Class Loading:
Execution phase:
Initialization:
jspService() execution:
jspDestroy() execution

  1. What if I write destroy method in jsp, will page destroy or show
  2. Dynamic vs static include
The syntax for static include is <%@ include file=”filename.jsp” %> and the syntax for dynamic include is <jsp:include page=”filename.jsp” />

  1. Difference between Scriptlet and Declaration
Declaration :- Used for declaring variables and methods.
example : <%!  int num =0;  %>
During translation and compilation phase of JSP life cycle all variables declared in jsp declaration become instance variables of servlet class and all methods become instance methods. Since instance variables are automatically initialized,all variables declared in jsp declaration section gets their default values.
Scriptlet:- Used for embedding java code fragments in JSP page.
example : <%  num++; %>
During translation phase of JSP Life cycle all scriptlet become part of _jspService() method. So we cannot declare methods in scriptlet since we cannot have methods inside other methods. As the variables declared inside scriptlet will get translated to local variables they must be initialized before use.

Hibernate
  1. Load V/S Get –
The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings. 

While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance


If load() can’t find the object in the cache or database, an exception is 
thrown. The load() method never returns null. The get() method returns
 
null if the object can’t be found.
 


  1. Cache implementation
  2. Composite key example
  3. Mappings in hibernate
  4. Xml based or annotation based
  5. hibernate_inheritance_strategy
  6. list vs set
  7. referred and owned collections
  8. use of cascade select and orphan removal
  9. hibernate API’s, query, criteria and hql.
  10. Session factory and session
  11. transaction managers
  12. configuring datasource



Spring
  1. Explain Spring DI and IOC
  2. Life cycle of spring bean.
  3. What happens if I have two beans of same name and using in service through injection
  4. Scope of beans
  5. Application context vs bean factory
  6. Spring aop
  7. Spring transactional management and programmatic management
  8. beanPostProcesssor
  9. singletone with dependency of prototype bean
  10. spring singleton vs java singleton
  11. @Autowired
  12. Spring MVC
  13. Init binders
  14. Validators


AJAX
  1. Make ajax request
  2. Get html in response.
  3. Async example
What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?
ReadWrite Lock is an implementation of lock stripping, where two separate locks are used for read and write operation. Since read operation doesn't modify state of object, it's safe to allow multiple access of shared object to multiple reader without locking, and by splitting lock into ReadLock and WriteLock, you can easily do that. Java provides an implementation of ReadWriteLock in form of ReentrantReadWritLock, which is worth looking. Also ConcurrentHashMap doesn't use ReadWriteLock, instead it divides maps into several segments and lock them separately using different locks, which means any given time, only a portion of map is locked, instead of whole map. This question is also very popular on Senior and experienced level Java interviews, expect Interviewer to go into more detail, e.g. asking you to provided an implementation of ReadWriteLock with different policies.

  1. How to make an Object Immutable in Java? Why should you make an Object Immutable?
    Well, Immutability offers several advantage including thread-safety, ability to cache and result in more readable multithreading code. See here to learn how to make object Immutable. Once again, this question can also go into more detail and depending upon your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.

    11) Which design patterns have you used?
    Always expect design and patterns related question for Senior developer Core Java Interview. It's best to mention any GOF design pattern rather than Singleton or MVC, which almost every other Java developer use it. Your best bet can be Decorator pattern or may be Dependency Injection Pattern, which is quite popular in Spring Framework. It's also good to mention only design pattern, which you have really used in your project and knows it's tradeoffs. As once you mention a particular design pattern say Factory, Interviewer's next question would be, have you used in your project? So be ready with proper example and why you choose a particular pattern.
14)  How  do you prevent SQL Injection in Java Code?
This question is more asked to Java EE developers than core Java developers but still a good question to know, PreparedStatement is the way to go. PreparedStatement not only provides better performance but also shield from SQL Injection attack. If you are working more on Java EE or J2EE side, than you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them.

Why Java doesn't support multiple inheritance

1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
           A foo()
           / \
          /   \
   foo() B     C foo()
          \   /
           \ /
            D
           foo()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

How do you detect deadlock in Java ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.

other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.


Why JDBC has all interfaces and no implementation classes
Securing URL parameters.
Sorting algorithms