Wednesday, September 25, 2013

Java interview questions for JP Morgan

1)How to store key, value in arraylist-
Ans) by putting map in genric to arraylist
2)Can we store class type object(map.put(new MyObject(),"two")) in hashmap - no, at runtime it wil return      error -
Ans) cannot be cast to java.lang.Integer
3)Can this happen-
Ans)    A a = new B(); - yes
  B b = new A(); - no , ascpet if it is explicitly casted - B b = (B)new A();
4)What is java reflection? how many ways are there to create objects -


Ans)
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
Java Reflection is quite powerful and can be very useful. For instance, when mapping objects to tables in a database at runtime, like Butterfly Persistence does. Or, when mapping the statements in a script language to method calls on real objects at runtime, like Butterfly Container does when parsing its configuration scripts.

5) JAVA JDBC connection steps:
     Class.forName("com.mysql.jdbc.Driver");
      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);


6) difference between preparedStatement and createStatment in JDBC 

In prepared statment DB server the execution plan get cached, performance will be better. It is a good way to code against SQL Injection as escapes the input values.