Monday 6 March 2017

Frequently asked java interview question and answers



Q. What are all the Object class methods?
A. equals, hashCode,toString,clone,wait,notify,notifyAll,getClass,finalize

Q. When do you go for Interface and abstract class?
A. When there is a complex logic to be used across the application, then provide that logic as a concrete method and place inside a abstract class as it allows both concrete and abstract methods. To get 100% abstraction, use interfaces in the application

Q. Write a psudo java code to print 1 to 10 numbers in sequence with two multiple threads in which one is printing even numbers and another is printing odd nos?
A. class Thread1 implements Runnable{

 @Override
 public synchronized void run() {
  for(int i=0;i<10 args="" auto-generated="" block="" catch="" class="" code="" e.printstacktrace="" e="" even="" evenoddthreaddemo="" for="" i="" if="" implements="" int="" main="" notify="" nterruptedexception="" numbers="" odd="" public="" r1="" r2="" run="" runnable="" static="" synchronized="" system.out.println="" t1.start="" t1="new" t2.start="" t2="new" thread1="" thread2="" thread="" todo="" tring="" try="" verride="" void="" wait="">

Q. What are the types of Inner Classes?
A. Anonymous inner class

Q. How to create a thread and which is best and why?
A. Using Thread© and Runnable(I)- Runnable is best as java does not support multiple inheritance.

Q. What is checked and unchecked exception?
A. Exception thrown by compiler - checked exception; exceptions thrown at runtime- unchecked exceptions

Q. Write the code to insert an element in ArrayList?
A. list.add(index, object)

Q. Differences between Array and ArrayList?
A. Array is fixed in size and allows homogenious elements Whereas ArrayList is growable and allows hetrogenious elements.

Q. What is HashMap ?
A. allows key and value pairs or entries

Q. Explain the internal implementation of HashMap?
A. It uses LinkedList data structures; when duplicate key found, will be replaced with update key; equals and hashCode should be overridden when custom objects are used.

Q. What is thread executor framework?
A. Used to call all multiple thread tasks with only one thread

Q. What is Serialization?
A. Sending objects over network. Objects will be converted to streams.

Q. How to synchronize a class?
A. We can use 'synchronized' key word along with a method, used for a block

Q. What is garbage collection?
A. All objects with no references will be collected by garbage collector

Q. How to customize garbage collection in Java?
A. I think we cannot. JVM will take care of it.

Q. What is Generics in Java?
A. Provides Type safety and avoid external type Casting

Q. Features of Java 8?
A. Default/static method Interfaces, Functional Interfaces, Lamda Expressions, Java Stream API and etc

Q. When there is a requirement to do frequent insertions and deletions, which collection is useful and why?
A. LinkedList as it is node based data structure

Q. what is the code to write Immutable object?
A. Need to make the class as final, and all fields must be either private or final.

Q. How to sort objects in java?
A. Using Comparable and Comparator

Q. Write the code to sort using Comparable?
A.
class Person implements Comparable{
    private String empName;
    private Integer empId;
    public Person(Integer id,String name){
     this.empId = id;
     this.empName = name;
    }
  
   @Override
   public int compareTo(Person e){
     return (this.empId - e.empId);
   }
  
    public String toString(){
     return empId+" "+empName;
     } }
    public class ComparableDemo {
   public static void main(String[] args) {
    Person e1 = new Person(3,"XXX");
    Person e2 = new Person(1,"YYYY");
    Person e3 = new Person(2,"ZZZ");
  
    List empList = new ArrayList();
    empList.add(e1);
    empList.add(e2);
    empList.add(e3);
  
    Collections.sort(empList);
  
    for(Person e:empList)
     System.out.println(e);
    }}

Q. When will you get StackOverflow Exception?
A. When we create an object inside a loop without having end condition

Q. What is final, finally, finalize?
A. final - a class with final cannot be subclassed - a final method cannot be overridden - a final variable cannot be re-initialized; finally - code gets executed irrespective of an exception occurred, its gets executed always except when System.exist(0) is used. finalize() - used before objects get garbage collected.

Q. Differences between throw and throws?
A. throw should be used along with throws but not vice versa. When developer develops custom exception, throw is useful to throw that exception.

Q. What is concurrent Map in java?
A. ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .
while HashMap is not thread-safe .

Q. What are all the oops conecpts and explain?
A. overloading,overriding; Encapsulation-gives security to the code/fields; Abstraction-hides the complexity of the code and just gives the functionality

Q. Which design patterns do you know?
A. MVC, Singleton, Factory, VO, DTO, FrontEndController

Q. What is implict object in jsp?
A. Ready made objects which needs no instantiation

Q. What are all the implicit objects in jsp?
A. request,response,session,out,application,page,pageContext,exception,config

Q. How to establish a connection in jdbc?
A. load the driver class, get the connection, create statement, prepare the query, execute the query, get the resultset object, iterate it and get the results or executeUpdate for non-select queries

Q. What are the types of Statements?
A. Simple sTatement, PreparedStatement, CallableStatement

Q. What is PreparedStatement and what is the advantage of it?
A. PreparedStatement allows to enter the values using setter methods and query will be compiled and placed at server side only once.

Q. Did you work on tuning queries/tables in db?
A. indexing, using views

Q. What are ACID properties?
A. Automicity, Consistency, Isolation, Durabiltiy

Q. How to get data from multiple tables?
A. Using joins - inner join, out joins-left and right, full join

Q. What are all the Isolation levels?
A. Read-only, Read-write…

Q. Which version of Hibernate used in your project?
A. 3.x

Q. What is hibernate configuration file?
A. a xml file where db related stuff, beans, hibenate mapping file gets configured.

Q. What is alternative for hibernate configuration?
A. We can use Java related api.

Q. What are all the hibenate properties?
A. dialect to show db equivalent qeuries, show-sql , hbm2ddl,…

Q.What is hibernate?
A. its an ORM tool where we can map a java class object with record in a table

Q. What are all the associations available in hibernate?
A. one-to-one; one-to-many;many-to-one;many-to-many

Q. What oops concepts are used in hibernate?
A.inheritance and association

Q. What is inverse="true"/"false"?
A. true-birectional association; false-uni-directional association

Q. What are all the generators in hibernate?
A. generates ids - assigned, sequence, increment…

Q. What are all the classes/interfaces used in hibernate?
A. Configuration, SessionFactory, Session, Transaction

Q. What are the states of object in hibenate?
A. Transient, Persistant, Detached

Q. what is get() and load() in hibernate?
A. get()- loads a class and returns null when specific object was not found; load()- loads class and return ObjectNotFound exception when the specific object not found.

Q. When the objects are moved to persistant state?
A. after session.flush()

Q. What is connection pool?
A. a pool of connection/session objects available and used connection will be moved to this pool.

Q. What is the use of connection pool?
A. Developer can use readily available session in his code.

Q. What is the Spring MVC flow?
A. request --> DispatcherServlet -->HandlerMaaping -->Controller--returns ModelAndView object>ViewResolver-->View

Q. What is bean?
A. Any simple java class with setters and getters.

Q. What are all the modules in spring?
A. Spring core, Spring MVC. Knowledge on remianing modules like Spring JDBC, Spring ORM, Spring AOP

Q. What is IOC or Inversion of control?
A. Design pattern stands for Inversion Of Control. Dependency Injection in spring describes one of the implementation of it.

Q. What is AOP?
A. Stands Aspect Oriented Programming. Useful in separating the business logic from all others like logging, exception handling, tx management

Q. Did you work at authorization part of application?
A. Not get a chance but aware of it. In Spring , Spring Security module is there to do so.

Q. What are the events in spring?
A. ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, RequestHandledEvent

Q. How to configure mail properties in spring?
A. Used spring given bean called ProperyPlaceHolderConfigurer. Added the mail.properties to the classpath. And retrieved them and added to "JavaMailSenderImpl" using ${}

Q. Why do we use ApplicationContext instead BeanFactory in Spring?
A. ApplicationContext supports all advanced features like events, i18n.,…

Q. What is Criteria api in Spring?
A. Used to put constraints on entity using static classes like Expressions,…

Q. How to call procedures and functions?
A. Used directly as native sql query and retrieved the results

Q. Do you why industry is prefering REST ?
A. for high performance in terms of fast and easy implementation

Run Postman API remote or code or command line

POSTMAN is used to run the APIs generally. What if we want to create a collection in postman and run it from some other code or command l...