Core Java Interview Questions and Answers - Freshers & Experienced!

What is Annotation in Java?

- An annotation, in the java programming language is a special form of syntactic metadata that can be added to Java Source Code.

- Classes, methods, variables, parameters and packages may be annotated.

- Unlike Java doc tags, Java annotation are reflective, in that they are embedded in class files generated by the compiler and may be retained by the java VM to make retrievable at run-time.

- Annotation is basically to attach metadata to method, class or package. Metadata is used by the compiler to perform some basic compile-time checking.

What is the difference between PreparedStatement and Statement in java?

- A statement is parsed and executed each time its call sent to database.
- A prepared statement may be parsed once and executed repeatedly with different parameters.
- There are four steps for the execution of query :
1. Query is parsed
2. Query is compiled
3. Query is optimized
4. Query is executed
- In case of statement, the above four steps are performed every time. And in case of prepared statement the above three steps are performed once.

What is CallableStatement? How you can call stored procedure to pass IN parameter?

- CallableStatement in java is used for calling database stored procedures.

- Example : Adding Employee details in DB whenever new Employee is joining.

- Employee Information : Employee Id, Name and joining Date.

- Code :
package com.mytest.jdbc;
import java.sql.CallableStatement;
import java.sql.DriverManager; import java.sql.Connection;
import java.sql.SQLException;

public class AddEmployeeExample
{
   private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
   private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MYTEST";
   private static final String DB_USER = "my_user";
   private static final String DB_PASSWORD = "my_password";
   public static void main(String[] argv)
   {
   try
   {
       addEmployeeInfo();
   }
   catch (SQLException e)
   {
       System.out.println(e.getMessage());
   }
}

private static void addEmployeeInfo() throws SQLException
{
   Connection dbConnection = null;
   CallableStatement callableStatement = null;
   String insertEmployeeStoreProc = "{call insertEmployee(?,?,?)}";
   try
   {
       dbConnection = getDBConnection();
       callableStatement = dbConnection.prepareCall(insertEmployeeStoreProc);
       callableStatement.setInt(1, 377602);
       callableStatement.setString(2, "Nishant Singh");
       callableStatement.setDate(3, getCurrentDate());
       // execute insert store procedure
       callableStatement.executeUpdate();
   }

   catch (SQLException exp)
   {
       System.out.println(exp.getMessage());
   }
   finally
   {
       if (callableStatement != null)
       {
          callableStatement.close();
       }
       if (dbConnection != null)
       {
          dbConnection.close();
       }
   }
}

private static Connection getDBConnection()
{
   Connection dbConnection = null;
   try
   {
       Class.forName(DB_DRIVER);
   }
   catch (ClassNotFoundException e)
   {
       System.out.println(e.getMessage());
   }

   try
   {
       dbConnection = DriverManager.getConnection( DB_CONNECTION, DB_USER,DB_PASSWORD);
       return dbConnection;
   }
   catch (SQLException e)
   {
       System.out.println(e.getMessage());
   }
     return dbConnection;
   }
   private static java.sql.Date getCurrentDate()
   {
       java.util.Date today = new java.util.Date();
       return new java.sql.Date(today.getTime());
   }
}

Using Callable Statement how can you pass OUT Parameters, explain with example?

Take the example of Employee, where you want the details of Employee by Id.

- Code : Use the same code structure get DB Connection etc.
//getDBUSERByUserId is a stored procedure

String getEmpInfoByEmpIdSql = "{call getEmpInfoByEmpId(?,?,?,?)}";

callableStatement = dbConnection.prepareCall(getEmpInfoByEmpIdSql);

callableStatement.setInt(1, 377602);

callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);

callableStatement.registerOutParameter(3, java.sql.Types.DATE);

// execute getEmpInfoByEmpId store procedure

callableStatement.executeUpdate();

String empName = callableStatement.getString(2);

String joiningDate = callableStatement.getDate(3);

Explain Java Thread Life cycle.

- The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.
- During its life cycle the thread moves from one state to another depending on the operation performed by it or performed on it.
- A Java thread can be in one of the following states:

1. NEW :
A thread that is just instantiated is in new state. When a start () method is invoked, the thread moves to the ready state from which it is automatically moved to runnable state by the thread scheduler.

2. RUNNABLE (ready_running) :
A thread executing in the JVM is in running state.

3. BLOCKED :
A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread performs an I/O operation and moves to next (runnable) state.

4. WAITING :
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

5. TIMED_WAITING (sleeping) :
A thread that is waiting for another thread to perform an action up to a specified waiting time is in this state.

6. TERMINATED (dead) :
A thread that has exited is in this state.

What are the different ways of creating thread?

There are two ways of creating thread.

1. Implementing Runnable :
The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example :
public class HelloRunnable implements Runnable
{
   public void run()
   {
       System.out.println("Hello from a thread!");
   }
   public static void main(String args[])
   {
       (new Thread(new HelloRunnable())).start();
   }
}
2. Subclass Thread :
The Thread class itself implements Runnable interface, though it runs method that does nothing. An application can subclass Thread, and provides its own implementation of run, as in the HelloThread example :
public class HelloThread extends Thread
{
   public void run()
   {
       System.out.println("Hello from a thread!");
   }
   public static void main(String args[])
   {
       (new HelloThread()).start();
   }
}

Which way a developer should use for creating thread, i.e. Sub classing Thread or implementing Runnable.

- There are two ways of creating Thread in java (i.e. sub classing or implementing Runnable).
- It is very important to understand the implication of using these two approaches.
- There are two different points about using these two approaches :

   1. By extending the thread class, the derived class itself is a thread object and it gains full control over the thread life cycle. Implementing the Runnable interface does not give developers any control over the thread itself, as it simply defines the unit of work that will be executed in a thread.
   2. Another important point is that when extending the Thread class, the derived class cannot extend any other base classes because Java only allows single inheritance. By implementing the Runnable interface, the class can still extend other base classes if necessary.

- To summarize, if developer needs a full control over the Thread life cycle, sub classing Thread class is a good choice, and if programs need more flexibility by extending other class developer, should go with implementing Runnable interface.

What is the use of Join method?

- The join method allows one thread to wait for the completion of another. If " t " is a Thread object whose thread is currently executing, t.join();
- It causes the current thread to pause execution until ' t’s ' thread terminates. Overloads of join allow the programmer to specify a waiting period.
- However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
- Like sleep, join responds to an interrupt by exiting with an InterruptedException.

What is the Difference between synchronized and synchronized block?

- In case of a Synchronized method a thread may need to have the lock for a longer time as compared to the synchronized block.
- Another difference between synchronized method and block is that we don’t specify the particular object whose monitor is required to be obtained by thread for entering a synchronized method, whereas we can specify the particular object in case of synchronized block.

Static Synchronization vs. Instance Synchronization?

- When a static synchronized method is called, the program obtains the class lock before calling the method.
- This mechanism is identical to the case in which method is non-static, it is just a different lock, and this lock is solely for static methods.
- Apart from the functional relationship between the two locks, they are not operationally related at all.

What will happen if non-synchronized method calls a static synchronized method and what kind of lock it acquires?

- If non-static synchronized method calls a static synchronized method it acquires both lock i.e. lock on the object and lock on the class level.
- Class lock does not actually exist the class lock, is the object lock of the “Class” object that models the class. Since there is only one “Class” object per class, using this object achieves the synchronization for static method.
1. Only one thread can execute a synchronized static method per class.
2. Only one thread per instance of the class can execute a non-static synchronized method.
3. Any number of threads can execute a non-synchronized method static or non-static method.

What is the use of volatile in Java?

- Threads are allowed to hold the values of variables in local memory (e.g. in a machine register).
- If a variable is marked as volatile, every time when the variable is used, it must be read from the main memory, similarly every time the variable is written, the value must be stored in main memory.
1 2 3 4

Purpose of the Runtime class - Core Java
What is the purpose of the Runtime class? - The java runtime system can be accessed by the Runtime class...
Static and a non-static inner class - Core Java
Difference between a static and a non-static inner class - Like static methods and static members are defined in a class, a class can also be static...
String vs. StringBuffer classes - Core Java
Difference between the String and StringBuffer classes - String class is immutable. The characters of string objects can not be changed / modified...
Post your comment
Discussion Board
java2novice.com
very nice. for more java examples, visit http://java2novice.com site
java2novice 04-21-2014
suggestion
When result of quiz is shown , please display the correct answer also . At present correct answer is shown only in case of incorrect answers .Sometimes , we guess the answer and it's right , so it would be helpful if correct answers are displayed in both cases i.e correct and incorrect
aarsha 07-5-2012
Core Java Interview questions and answers
What is a Map? What are the implementations of Map?
Map is an interface that provides three collection views, which allows the map’s content to be viewed in different forms like set of keys, collection of values, or set of key-value mappings. It is an object interface that allows the associations between keys and values.
The implementations of Map are as follows:
- HashMap
- HashTable
- TreeMap
- EnumMap

What is java’s garbage collected heap?
JVM is also known as Java Virtual Machine. It is the heart of JAVA programming language. JVM’s heap stores all the objects that have been created and ready for execution. When an object is created by “new()” operator then the memory is being allocated on heap at run time. JAVA is having the concept of “Garbage collection” to automatically free the objects when they are no longer referenced by a program. This allows the programmer not to worry about the freeing of allocated memory.
Rohit Sharma 12-19-2011
Core Java Interview questions and answers
What are static methods?
Static methods are the methods, which are declared with the keyword as static. These methods are the modifiers for the class methods. They are used to affect the entire class not the instance of it. These methods are always invoked without reference to a particular instance of a class. The restrictions that have been imposed are as follows:
- A static method can only call and access other static methods and data respectively.
- A static method cannot reference to the current object using keywords “super” or “this”.

What is an Iterator?
Iterator is an interface that is used to loop through the elements from the collection. It allows you to go through each element in the collection and lets you organize and manage all the elements. This is different for different methods and it is used differently in different conditions. Iterator is not as same as enumeration, but it takes the place of enumeration in the Java Framework.

What is the Set interface?
Set interface is a collection that can’t contain duplicate elements. It provides the abstracted method and contains only methods that are inherited from collection. It adds the restriction on duplicate elements. It does the comparison that two sets of objects are equal if they contain the same elements. Java consists of three implementation of it, those are as follows:
- HashSet: stores its element in hash table
- TreeSet: store its element in the tree form
- LinkedHashSet: implemented as a hash table with a linked list running through it
Rohit Sharma 12-19-2011
Core Java Interview questions and answers
What is method overloading?
Method overloading is a type of polymorphism that includes two or more methods with the same name in same class but, the condition is that it should have different arguments, otherwise an error might occur. This method overloading is very advantageous, as it allows you to implement many methods with the same syntax and semantics. The Overloaded methods that should follow the criteria are as follows:
- Overloaded methods can change the return type and access modifier
- Overloaded methods can declare new or broader checked exceptions
- A method can be overloaded in the same class or in a subclass

What is method overriding?
Method overriding is a type of polymorphism that is different from the overloading method, as it allows you to declare the method with the same arguments. The advantage of using this is that it defines the behavior of the specific subclass. It doesn’t provide very strict restrictive access modifier. The method that marked as public and protected can’t be overridden. You also cannot override a method marked final and static.

What is super?
super() is a keyword used in Java language. This keyword is used to access the method and member variables of the super-class. It can refer the member or the hidden variable of the super-class. It can also invoke the overridden method. super() should be used to access the hidden variable and it should be the first keyword written in the constructor.
Rohit Sharma 12-19-2011
Core Java Interview questions and answers
Explain different forms of Polymorphism?
Polymorphism allows the values of different data types to be handled using a uniform interface. There are two types of polymorphism present. One is compile time polymorphism that includes method overloading function. Another one is run time polymorphism that includes inheritance and interface. The three different forms used in java are as follows:
- Method overloading
- Method overriding through inheritance
- Method overriding through the Java interface

What is runtime polymorphism or dynamic method dispatch?
Runtime polymorphism is also known as dynamic method dispatch. It is a process that calls to an overridden method to resolve the complexity at runtime, not during compile time. This overridden method is called through reference variable of a super-class (i.e. the root class). Determination of the method is based on the object that is being referred by the reference variable of the super-class.
Rohit Sharma 12-19-2011