40 Core Java Interview Questions and Answers - Freshers, Experienced

Dear Readers, Welcome to Core Java Interview questions with answers and explanation. These 40 solved Core Java questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky Core Java questions, you can easily attempt the objective type and multiple choice type questions on this subject.

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.

How static variable work in java?

- Static code is loaded before the class is instantiated and stays in memory until the JVM exits as opposed to instance variable which are loaded and unloaded, is called as “Dynamic” code.
- Each class has one copy of each of its static members in memory.
- Each instance of the class has access to that single static memory location.
- The single member is same for every instance.
- Static member does not have access to instance members.

What is Contract between hashcode and equal method?

- The Java super class java.lang.Object has two very important methods defined.
public boolean equals(Object obj)
public int hashCode()
- It is very important to understand the contract between equals and hashcode. The general contract of hashCode is whenever hashCode method is invoked on the same object more than once during the execution of the application, the hashCode method consistently return same integer value.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

What is Hash Code collision?

The idea of hashing is to store an element into an array at a position index computed as below :
1. Obtain element_hash_code of the element by processing the element's data and generating an integer value.
use a simple mod operation to map into the array's range: index = hash(element) = abs(element_hash_code % array_capacity)
2. The hashcode collision occurs when the index calculated by hash function results same for two or more elements.

What is Re-factoring in Software?

- Re-factoring is the continuous process of changing a software system in such a way that it does not alter the external behavior of the code yet improves the internal structure of the code.
- It is advisory that developers should have habit to apply re-factoring as continuous process to improve the code structure.
- Re-factoring helps to keep the code clone and minimize the chances of introducing bugs.
- Re-factoring made the internal structure of the software, easier to understand and cheaper to enhance the functionality of the software.
Note : There are different types of Re-factoring, to know more about re-factoring read re-factoring, improvement of existing code by Martin Fowler.

What is Singleton Pattern?

- The Singleton pattern ensures that class has only one instance and provides a global point of access to it.
Example : This is simple example which will return single instance.
public class Singleton
{
   private static Singleton uniqueObj;
   // Private Constructor so that no instance can be created.
   private Singleton(){ }
   public static Singleton getInstance()
   {
      if(uniqueObj==null)
      {
        uniqueObj = new Singleton();
      }
      return uniqueObj;
   }
}

How can you make sure that your singleton class will always return single instance in multi-threaded environment?

There are three ways to make your class singleton.
1. Simple way, create a private object and do null check, if object is null create the instance otherwise return the same instance, refer above example in previous question. Singleton class created this way will not guarantee that it will work properly in multi-threaded enviornment.

2. By creating global static variable of the same class and instantiate it at the time of declaration. The Singleton class created this will work perfectly in multi-threaded enviornment.
Example :
public class Singleton
{
   // global instance created and instantiated at the time of declaration.
   private static Singleton uniqueObj = new Singleton();
   // Private Constructor so that no instance can be created.
   private Singleton(){ }
   public static Singleton getInstance()
   {
       return uniqueObj;
   }
}

3. Creating class by double checking. This is the best way of creating Singleton class which will work perfectly in multi-threaded environment also.
public class Singleton
{
   private static Singleton uniqueObj;
   // Private Constructor so that no instance can be created.
   private Singleton(){}
   public static Singleton getInstance()
   {
       if(uniqueObj==null)
       {
          syncronized(Singleton.class)
          {
             if(uniqueObj==null)
             {
                uniqueObj = new Singleton();
             }
          }
       }
       return uniqueObj;
   }
}

Why Singleton pattern is better than creating Singleton class with static instance?

- With Singleton pattern you can create an object when you require, but a static instance gets created at the time of class loading i.e. we can easily instantiate object with singleton pattern.
- With Singleton pattern we can use inheritance, for example when we require default behavior of the Singleton class then we can use that, with static you cannot.

What is Covariant Return Type?

The Covariant return type were introduced in java-5. Before Java 5, it was not possible to override method whose return type is different from the super class method. But with java 5 you can override method by changing the return type to subclass type and this rule is applicable for the methods whose return types are non-primitive.
Example :
class SuperClass
{
   SuperClass get(){return this;}
}
class SubClass extends SuperClass
{
   SubClass get(){return this;}
   void printMessage()
   {
       System.out.println("This is covariant return type");
   }
   public static void main(String args[])
   {
       new SubClass().get().printMessage();
   }
}
Output : This is covariant return type.
- From the above example, you can see that the return type of SuperClass get method is SuperClass and the same method get is overriden in SubClass and whose return type is of Subclass.
- So as you can see that the get method overridden has a different return type. This feature is known as Covariant return type.

When is finally block NOT called?

Finally block is NOT called in following cases :
- If the JVM exits while the try or catch code is being executed. This may happen due to System.exit() call.
- If the thread executing the try or catch code gets interrupted or killed. In this case, the finally block may not execute although the application keeps working.
- If an exception is thrown in finally block is not handled. In this case, the remaining code in finally block may not execute.

Which package is imported by default?

java.lang package is imported by default. It is imported even without a package declaration.

If you do not want your class to be inherited by any other class. What would you do?

- Declare your class as final . A class declared as final can't be inherited by any other class.
- However, if it is an abstract class, you can't define your class as final.

What is the difference between final, finally and finalize()?

final :
- It is a modifier which can be applied to a class, method or variable.
- It is not possible to inherit the final class, override the final method and change the final variable.

finally :
- It is an exception handling code section.
- It gets executed whether an exception is raised or not by the try block code segment.

finalize() :
- It is a method of Object class.
- It is executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

Can we declare a static variable inside a method?

No, static variables can’t be declared inside a method otherwise the class will not compile.

Tell us something about different types of casting?

There are two types of casting :
a. Casting between primitive numeric types
b. Casting between object references
- Casting between numeric types is used to convert larger values into smaller values. For e.g. double values to byte values.
- Casting between object references helps you refer to an object by a compatible class, interface, or array type reference.

What is Downcasting?

Downcasting means casting from a general to a more specific type.

What do you mean by order of precedence and associativity?

Order of precedence : It determines the order in which the operators in an expression should be evaluated.
Associativity : It determines whether an expression should be evaluated left-to-right or right-to-left.

If a class is declared without any access modifiers, where can the class be accessed?

- A class declared without any access modifiers is said to have package access.
- Such a class can only be accessed by other classes and interfaces defined within the same package.

Tell us something about an Iterator.

- The Iterator interface is used to step through the elements of a collection.
- It lets you process each element of a Collection.
- They are a generic way to go through all the elements of a Collection.

How do constructors use this() and super()?

this() : It is used to refer to another constructor in the same class with a different parameter list.
super() : It is used to invoke the superclass's constructor.

Explain numeric promotion?

- Conversion of a smaller numeric type to a larger numeric type is called numeric promotion.
- This helps in carrying out integer and floating-point operations.
- Byte, char and short values are converted to int values in numeric promotion.
- int values are converted to long values, if required.
- The long and float values are converted to double values, if required.

What is final modifier?

The final modifier keyword that the programmer cannot change the value anymore. Following is what happens when it is applied on classes, variables or methods,
final classes - A final class cannot have subclasses.
final variables - Once initialized, a final variable cannot be changed.
final Methods - A final method cannot be overridden by subclasses.

What are the restrictions imposed on method overriding?

- Overridden methods must have the same name, argument list and return type.
- The overriding method can not limit the access of the method overriden.
- The overriding method can not throw any exceptions that overridden method doesn’t throw.

When should you use ArrayList and when should you use LinkedList?

- If you need to support random access, without inserting or removing elements from anywhere other than the ends, then ArrayList is a better choice.
- If you add and remove elements from the middle of the list frequently while accessing them sequentially, then LinkedList is better.

What are the different collection views provided by Maps?

Maps provide three collection views :
1. Key Set : It allows a map's contents to be viewed as a set of keys.
2. Entry Set : It allows the contents of a map to be viewed as a set of key-value mappings.
3. Values Collection : It allows a map's contents to be viewed as a set of values.

Tell us something about set interface.

- The Set interface provides methods to access the elements of a finite mathematical set.
- Duplicate elements are not allowed by sets.
- It contains only the methods inherited from collection
- If two Set Objects contain same elements, they are said to be equal.

What is the difference between a constructor and a method?

Method is just an ordinary member function which consists of its own return type (can be a void), name and always invoked by a dot operator whereas a constructor is the member function of that class which is used to create objects in it, the name of the class and constructor is always same, no return type and always invoked by a new operator.

Write a code to show a static variable

class customer
{
   int a; //initialized to zero
   static int b; //initialized to zero only when class is loaded not for each object created

   customer()
   {
       //Constructor incrementing static variable b
       b++;
   }

   public void showData()
   {
       System.out.println("Value of a = "+a);
       System.out.println("Value of b = "+b);
   }
   //public static void increment()
   {
       //a++;
   }
}
class Demo
{
   public static void main(String args[])
   {
      customer c1 = new customer();
      c1.showData();
      customer c2 = new customer();
      c2.showData();
      //customer.b++;
      //c1.showData();
   }
}
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

What do you understand by Soft reference?

A soft reference can be defined as an object which does not have a path which has no weak references but has soft references, i.e. it is an object which is not strongly reachable. At times the garbage collector might reclaim a softly reachable object which totally depends on how recently they were accessed. But as if a heap running low then it is required to clear all soft references as it is affecting the speed, no matter those soft references were used lately or not.

What do you understand by weak reference?

A weak reference can explain as an object which neither have a strong reference nor a soft reference but have at least had one or two paths to the object with a weak reference. The only difference between a weak and a soft reference is their reclamation by the garbage operator, an algorithm is used to reclaim a soft reference whereas a weak is reclaimed always.

Are the imports checked for validity at compile time? Will the code containing an import such as java.lang.ABCD compile?

Yes, at the time compilation, imports are checked for semantic validity, the code will not compile, as it will show an error saying “cannot resolve symbol”.
symbol : class ABCD
location : package io
import java.io.ABCD;

What is the common usage of serialization? What exceptions occur during serialization?

- The object need to be serialized when it’s sent over a network and when it’s state is saved.
- Exceptions which occur during serialization are :
a. Transient fields.
b. When the base class is serialized then only base class fields are handled.
c. Static fields are ignored because they are not part of any state.

Can a top level class be private or protected?

No, a top level class can neither be private or protected If it does not have a modifier it is supposed to have a default access so it can be public or no modifier. If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here", which means that a top level class cannot be private. Same case is followed for protected also.

How are Observer and Observable used?

List of observers are maintained by the objects that are subclasses the observable class. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, is the highest priority task which is executed until it enters the waiting or dead states or a higher priority task. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Is there any difference between synchronized methods and synchronized statements?

The method used to control access to an object is called synchronized method. It is only executed by a thread, after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. So there’s not much difference between synchronized methods and synchronized statements.

How applets communicate with each other?

Applets may communicate with other applets running in the same virtual machine but it’s not necessary that they communicate. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

Mention the default values of all the elements of an array defined as an instance variable.

If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type whereas if the array is an array of references (of any type), all the elements will be initialized to null.. e.g. All the elements of an array of int will be initialized to 0, while that of Boolean type will be initialized to false.

What are the steps in the JDBC connection?

Following steps are followed while making a JDBC connection :

Step 1 : database driver is registered by the below written code :
Class.forName(\" driver class for that specific database\" );

Step 2 : Then database connection is created using :
Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Finally the query is executed :
stmt.executeUpdate();

What are some alternatives to inheritance?

To include an instance of another class as an instance variable, and forward messages to the instance is an alternative to inheritance which is also called delegation. Most of the time it is safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class. It doesn't force you to accept all the methods of the super class : On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

State the difference between creating String as new () and literal.

- When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
- String s = new String("Test"); will put the object in String pool , it does then why do one need String.intern() method which is used to put Strings into String pool explicitly. It’s only when you create String object as String literal e.g. String s = "Test" it put the String in pool.

What is the similarity between Dynamic Binding and linking?

Dynamic binding is orthogonal to dynamic linking. Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding It is associated with polymorphism and inheritance, it(also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time.

What is dynamic method dispatch?

Dynamic method dispatch which is also known as runtime polymorphism is a process
in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

What is a prefix function.write down a code to compute prefix function.

computeKmpPrefix(const std::string &pattern)
{
   int patternSize = pattern.size();
   vector<int> kmpPrefix(patternSize);
   size_t prefixPos = 0;
   size_t suffixPos = 1;
   while(suffixPos < patternSize)
   {
       if(pattern[prefixPos] == pattern[suffixPos])
       {
          kmpPrefix[suffixPos] = prefixPos + 1;
          prefixPos++;
          suffixPos++;
       }
       else if(prefixPos > 0)
       {
          //found some match
          prefixPos = kmpPrefix[prefixPos -1];
          //backtrack for matching prefix e.g. aaaaabaaaaaa
       }
       else
       {
          kmpPrefix[suffixPos] = 0;
          suffixPos++;
       }
   }
return kmpPrefix;
}

How transient variable is different from volatile variable?

Transient modifier applies to variables only and it is not stored as part of its objects persistent state. Transient variable can't be serialized. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Volatile modifier applies to variables only and tells the compiler that the variable modified by volatile can be changed unexpected by other parts of the program.

Write a code to create a trigger to call a stored procedure

Following code is an example of creating a trigger to call a stored procedure :
create trigger contact_t4
before insert on contact
for each row
when (new.member_id is not null)
begin
java_contact_t4 (:new member_id);
end;
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