Java Interview Questions

Planning to switch my current job, I ended up giving a few telephonic interviews all of which were JAVA based related to either what I was doing or general core java questions. I will here mention the ones I can recall.

 

1. What are hashCode() and equal() methods and why are they used (Most asked question :P)

A. These are the methods provided by the Object class to establish the identity of the object. Its a common convention that if one is overriden, the other is also.

– The hashcode() MUST consistently return the same integer when it is invoked on the same object more than once during the execution of a java application. The return value can vary with subsequent executions.

– Calling hashcode() on two objects must return same integer when it is called on two objects that are equal according to the equals() method.

– It is NOT necessary that if two objects are unqual according to equals() method, then hashcode() must produce different results.

 

2. What are checked and unchecked exceptions? How is an error different from an exception?

A. An exception is a problem when a program is running which is caused by the circumstances outside the control of the program. When the exception occurs, the JVM creates an object of Exception class which holds the information about the problem. Program may catch the exception and use the exception object to recover from the problem

Error is a problem when program is running which is represented by an object of class Error. It is too severe for a program to handle and the program must stop running.

Both Error and Exception extend Throwable which comes from Object.

– Checked exceptions extend Exception class while Unchecked exceptions extend RuntimeException Class.

– A method is not obligated to establish a policy for the unchecked exception thrown by its implementation. An Unchecked exception represents a bug/defect in a program and the the program usually halts after encountering an unchecked exception. NoClassDefFoundError is an example of an Unchecked exception.

– A method has to necessarily provide policy to handle checked exceptions. Checked exceptions allow the program to recover after the exception has been thrown. This usually represents bad user input or invalid parameters. ClassNotFoundException is an example of exception.

 

3. Difference between ClassNotFoundException and NoClassDefFoundError?

A. ClassNotFoundExceptions: This is an exception which is thrown when an application tries to load a class through the string name of the class using any of the following methods

– the forName() method in class Class

– the findSystemClass() method in ClassLoader class

– the loadClass() method in the class ClassLoader

NoClassDefFoundError: This is thrown if JVM or the ClassLoader instance tries to load in a definition of a class(as a part of normal method call or as a part of creating a new expression) and no definition of the class could be found. The searched for class definition existed when the currently executing class was compiled, but the definition could no longer be found. This is an error.

4. Difference between sorting algorithm of Collections.sort() and Arrays.sort() ?

A. They have same sorting algorithm. The only difference is the type of input to them. Collections.sort() has the input as a list and so it does a translation of List to Array and vice versa which is an additional step while sorting. So this should be only used when one is trying to sort a list. Arrays.sort() is for sorting arrays and so sorting is done directly on array.

5. What are the Collections Framework Interfaces?

A. Core Collection Interfaces are :

– Collection- root of the collection hierarchy. This represent group of objects known as elements.

– Set: It is a Collection that cannot contain duplicate elements. It contains ONLY methods inherited form Collection and adds the restriction that duplicate elements are prohibited. This models mathematical set abstraction.

– List: It is an ordered Collection. It can contain duplicate elements . User has control as to where in the list exactly the element has to be inserted and it can be accessed by index. It includes operations for – positional access, search, iteration, range-view.

Queue: It is a Collection to hold multiple objects. This provides additional insertion, extraction and inspection operations. Priority queues hold objects in order according to the supplied comparator. Every queue implementation MUST provide its ordering properties.

Map: maps keys to values. Map cannot contain duplicate values

SortedSet: A set that maintains its elements in ascending order

SortedMap: A map that maintains its mapping in ascending key order

 

6. Difference between Arrays and ArrayLists ?

A.  – Arrays cannot change their size during runtime, while ArrayLists can

– Objects cannot be stored in Arrays. They only permit primitive data types. Arraylists can ONLY store objects, not primitive data types.

– Array is an Object and it stores the elements of same type; ArrayList is a Collection which can be used to store objects on any data type

– Once an object is deleted from an Array, the corresponding position becomes empty but the index remains, while if an Object is deleted from ArrayList, then the whole list shifts one position.

 

7. How to create a DB connection?

A. To create a DB connection, following steps are followed:

  1. Load the database class e.g. Class.forName(“org.sqlite.JDBC”);

  2. Create connection e.g. Connection conn = DriverManager.getConnection(“jdbc:sqlite:/path/to/db.sql”);

  3.  Create an Sql query in String e.g String sql = select * from users;

  4.  Create Prepared Statement e.g. PreparedStatement ps = conn.prepareStatement(sql);

  5.  Execute the query over the connection e.g. ps.execute();

8. Difference between Callable and PreparedStatements?

A. PreparedStatements are the subclass of Statement class. Unlike Statement, PreparedStatement is compiled and optimized once and can be used multiple times by setting different parameter values. When a PreparedStatement is run, the DBMS can just run the statement without compiling it first.

CallableStatement Object provides a way to call stored procedures in standard way for all the DBMS’s. User has to just name the stored procedure and provide the parameters, if any.

9. How to extract values from a table in DB and set parameters in the query?

A. The first two steps for creating the connection are the same as in answer to question 7.

  1. Create the query e.g. String sql = “select * from users where user_id = ?”;

  2. Create PreparedStatement e.g. PreparedStatement ps = conn.prepareStatement(sql);

  3. Set the parameter in statement e.g. ps.setInt(1, userId); //userId variable is set by other program logic

  4. Execute and fetch the result e.g ResultSet rs = ps.executeQuery(); // rs now contains the result

7 Extract relevant value from rs e.g

if(null != rs){

while(rs.hasNext()){

String userName = rs.getString(2);//assuming the second column contains user name

}

}

These actually cover a very wide range of core JAVA questions. There are some more which were asked to me and I will put them up in the next post. Need a break right now 🙂

 

Credits:

  1. http://www.allapplabs.com/interview_questions/java_interview_questions.htm

  2. Stack Overflow

  3. Official Java Documentation on Oracle

Share Comments
comments powered by Disqus