83 core java interview questions and answers

Core Java interview questions and answers for freshers and experienced candidates. These interview questions and answers on Core Java will help you strengthen your technical skills, prepare for the interviews and quickly revise the concepts. Many candidates appear for the interview for one role - many of the them give the right answers to the questions asked. The one who provides the best answer with a perfect presentation is the one who wins the interview race. The set of Core java interview questions here ensures that you offer a perfect answer to the interview questions posed to you.
          

Core java interview questions and answers


Part 1   Part 2   Part 3   Part 4   Part 5
<<Previous  Next>>

Core Java interview questions - posted on Feb 04, 2014 at 11:40 AM by Nihal Singh

Q: 1 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.

Q: 2 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.

Q: 3 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());
      }
}

Q: 4 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);

Q: 5 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:

  • 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.
  • RUNNABLE (ready_running) A thread executing in the JVM is in running state.
  • 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.
  • WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • 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.
  • TERMINATED (dead) A thread that has exited is in this state.

Q: 6 What are the different ways of creating thread?

There are two ways of creating thread.

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();
    }
}

Subclass Thread. The Thread class itself implements Runnable interface, though it runs method 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();
        }
}

Q: 7 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.

  • 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.
  • 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.

Q: 8 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();

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.

Q: 9 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.

Q:10 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 method.

Apart from the functional relationship between the two locks, they are not operationally related at all.

Q: 11 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.

  • Only one thread can execute a synchronized static method per class.
  • Only one thread per instance of the class can execute a non-static synchronized method.
  • Any number of threads can execute a non-synchronized method static or non-static method.

Q:12 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.

Q:13 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 which is called “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.

Q: 14 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.

Q: 15 What is Hash Code collision?

The idea of hashing is to store an element into array at a position index computed as below.

  • 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)

The hashcode collision occurs when the index calculated by hash function results same for two or more elements.

Q.16 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 internal structure of the code.

It is advisory that developer 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 bug.

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.

Q. 17 What is Singleton Pattern?

The Singleton pattern ensures that class has only one instance and provides a global point of access to it.

Example 1. 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;
    }
}

Q. 18 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.

  • Simple way, create private object and do null check, if object is null create the instance otherwise return the same instance, refer example 1 in previous question. Singleton class created this way will not guarantee that it will work properly in multi-threaded enviornment.
  • 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; 
        }
    }
  • 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;
      }
    }

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

With Singleton pattern you can create the object when you required, but static instance get created at the time of class loading i.e. we can lazily 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.

Q: 20 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 different return type. This feature is known as Covariant return type.

Core Java interview questions - posted on June 27, 2013 at 15:40 PM by Kshipra Singh

1. What is a pointer? Does Java support pointers?

- Pointer means a reference handle to a memory location.
- Java doesn't support the use of pointers as their improper handling causes memory leaks and compromises the reliability.

Core Java interview questions and answers for freshers  

2. Differentiate between Path and Classpath?

- Path and Classpath both are operating system level environment variables.
- Path tells where can the system find the executable(.exe) files while classpath provides the location .class files.

Core java interview questions and answers for experienced

3. Is it necessary to declare main() method compulsorily in all java classes?

- No, it is not.
- main() method needs to be defined only if the source class is a java application.

4. What is the use of the finally block?

Finally is the block of code that is always executed even when an exception has occurred.

Core Java interview practice test - 20 questions
Core Java interview practice test - 10 questions

Core Java  interview test (72 questions) new
-By Pradip Patil, Lecturer IIMP MCA

Java  (20 questions) new
-By Pradip Patil, Lecturer IIMP MCA

5. 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.

6. Which package is imported by default?

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

7. 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.

8. 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.

9. 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.

10. 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.

11. What is Downcasting ?

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

12. 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.

13. 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.

14. 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.

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

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

16. 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.

17. 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.

18. 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.

19. 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.

20. What are the different collection views provided by Maps?

Maps Provide Three Collection Views:
a.) Key Set – It allows a map's contents to be viewed as a set of keys.
b.) Entry Set – It allows the contents of a map to be viewed as a set of key-value mappings.
c.) Values Collection – It allows a map's contents to be viewed as a set of values.

21. 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.

1.What is the purpose of the Runtime class?

Latest answer: The java runtime system can be accessed by the Runtime class. The runtime information – memory availability, invoking the garbage collector is possible by using Runtime class............
Read answer

2.What is the difference between a static and a non-static inner class?

Latest answer: Like static methods and static members are defined in a class, a class can also be static. To specify the static class, prefix the keyword ‘static’ before the keyword ‘class’...........
Read answer

3.What is the difference between the String and StringBuffer classes?

Latest answer: String class is immutable. The characters of string objects can not be changed / modified. StringBuffer is mutable. The characters of StringBuffer objects can be modified / changed..........
Read answer

4.What is the Dictionary class?

Latest answer: The Dictionary class is an abstract class. The class maps keys to values. The classes such as HashTable are the sub classes of the abstract class Dictionary. The key and values are objects. The key and value are non-null objects...............
Read answer

5.What is the ResourceBundle class?

Latest answer: A ResourceBundle is a group of related sub classes which are sharing the same base name. For example, ButtonLabel is the base name. All the characters following the base name indicates the following elements respectively...........
Read answer

6.What is the Vector class?

Latest answer: The Vector class implements an incremental array of objects.
The vector components can be accessed using an integer index.
The size of a Vector increases or decreases as needed to accommodate the items.........
Read answer

7.What is the SimpleTimeZone class?

Latest answer: SimpleTimeZone is a concrete subclass of TimeZone class. The TimeZone class represents a time zone, that is to be used with Gregorian calendar..........
Read answer

8.What is the purpose of the System class?

Latest answer: System class is provided with useful fields (static members) that are pertaining to the environment. Standard input,output and error output streams are provided with System class. These are used to access the externally defined properties and environment variables............
Read answer

9.How are this() and super() used with constructors?

Latest answer: this() constructor is invoked within a method of a class, if the execution of the constructor is to be done before the functionality of that method............
Read answer

10.What is the purpose of finalization?

Latest answer: Finalization is the facility to invoke finalized() method. The purpose of finalization is to perform some action before the objects get cleaned up. This method performs the required cleanup before the garbage collection.............
Read answer

11.What is the difference between the File and RandomAccessFile classes?

Latest answer: The File class is used to perform the operations on files and directories of the file system of an operating system. This operating system is the platform for the java application that uses the File class objects............
Read answer

12.What is a StringBuffer class and how does it differs from String class?

Latest answer: StringBuffer is thread safe, where as StringBuilder is not. In other words, StringBuffer class is synchronized and StringBuilder class is not synchronized..........
Read answer

13.Explain how to implement shallow cloning and deep cloning.

Latest answer: Implementing Shallow cloning: In shallow cloning, a new object is created which is an exact copy of the original object. It is a bit-wise copy of an object. In case any field of the object is referred to other objects, only the references are copied but not the objects............
Read answer

14.What is an abstract class? | Explain the difference between abstract class and interfaces.

Latest answer: An abstract class defines an abstract concept which can’t be instantiated. We can’t create object of abstract class, it can only be inherited. Abstract class normally represents concept with general actions associated with it.................
Read answer

15.What is an interface?

Latest answer: An interface is a set of method definition without implementation. It is a protocol of behavior for a class.................
Read answer

16.Explain JVM (Java virtual machine) and JIT (Just in compilation).

Latest answer: JVM is a virtual computer that runs the compiled java program. JVM is software that stays on the top of the operating system and provides abstraction between the compiled java program and operating system.............
Read answer

17.Explain how to implement polymorphism in JAVA.

Latest answer: Capacity of a method to do different things based on the object that it is acting upon is called as polymorphism.............
Read answer

Core Java Interview questions with answers posted on August 11, 2008, 19:00 pm by Amit Satpute
18.What are Native methods in Java?

Latest answer: Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.............
Read answer

19.What are class loaders?

Latest answer: The class loader describes the behavior of converting a named class into the bits responsible for implementing that class............
Read answer

20.What is Reflection API in Java?

Latest answer: The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes allow you to call another class's methods dynamically at run time..........
Read answer

21.Explain the difference between static and dynamic class loading.

Latest answer: The static class loading is done through the new operator. Dynamic class loading is achieved through Run time type identification. Also called as reflection............
Read answer

22.Explain Shallow and deep cloning.

Latest answer: Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example............
Read answer

23.What is the purpose of Comparator Interface?

Latest answer: Comparators can be used to control the order of certain data structures and collection of objets too. The interface can be found in java.util.Comparator.............
Read answer

24.Explain the impact of private constructor.

Latest answer: Private Constructors can't be access from any derived classes neither from another class. So you have to provide a public function that calls the private constructor...........
Read answer

25.What are static Initializers?

Latest answer: A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition............
Read answer

26.Explain autoboxing and unboxing.

Latest answer: To add any primitive to a collection, you need to explicitly box (or cast) it into an appropriate wrapper class.It is not possible to put any primitive values, such as int or char, into a collection. Collections can hold only object references...........
Read answer

27.What is Map and SortedMap interface?

Latest answer: Keys will be mapped to their values using Map object. Map allows no duplicate values. The keys in a map objects must be unique. Java collection framework allows implementing Map interface in three classes namely, HashMap, TreeMap and LinkedHashMap.............
Read answer

28.Define the purpose of Externalizable Interface.

Latest answer: The Externizable interface extends the serializable interface.
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process............
Read answer

29.What is transient and volatile modifiers?

Latest answer: When serializable interface is declared, the compiler knows that the object has to be handled so as so be able to serialize it. However, if you declare a variable in an object as transient, then it doesn’t get serialized. ..........
Read answer

30.What are daemon threads?

Latest answer: Threads that work in the background to support the runtime environment are called daemon threads.............
Read answer

31.What is JAVAdoc utility?

Latest answer: Javadoc utility enables you to keep the code and the documentation in sync easily. The javadoc utility lets you put your comments right next to your code, inside your ".java" source files............
Read answer

32.Explain the difference between StringBuilder and StringBuffer class.

Latest answer: StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer...........
Read answer

33.Explain semaphore and monitors in java threading.

Latest answer: A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process...........
Read answer

34.What are Checked and UnChecked Exception?

Latest answer: The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions non runtime exceptions and runtime exceptions...........
Read answer

35.What are different types of inner classes?

Latest answer: Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration............
Read answer

36.Why do we need wrapper classes?

Latest answer: Wrapper classes allow primitive data types to be accessed as objects. They are one per primitive type: Boolean, Byte, Character, Double, Float, Integer, Long and Short. Wrapper classes make the primitive type data to act as objects.........
Read answer

37.What is the difference between error and an exception?

Latest answer: Errors are abnormal conditions that should never occur. Not to be confused with the compile time errors............
Read answer

38.What is the difference between preemptive scheduling and time slicing?

Latest answer: Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors............
Read answer

39.What is serializable Interface?

Latest answer: If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred........
Read answer

40.How does thread synchronization occurs inside a monitor?

Latest answer:   A Monitor defines a lock and condition variables for managing concurrent access to shared data.......
Read answer

41.What is the difference between AWT and Swing?

Latest answer: Classes in swing are not OS dependent. They don’t create peer components,..........
Read answer

42.What is meant by Stream Tokenizer?

Latest answer: The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time...............
Read answer

43.What is meant by getCodeBase and getDocumentBase method?

Latest answer: The getCodebase() method is also commonly used to establish a path to other files or folders that are in the same location as the class being run.............
Read answer

<<Previous  Next>>

More Java related questions

Portal and Portlet

What is a Portlet? Explain its capabilities.
Explain Portal architecture.
What is PortletSession interface?
What is PortletContext interface?
Why portals?..............

Java Authentication and Authorization Service, JAAS

What is Java Authentication and Authorization Service, JAAS?
Features of JAAS.
JAAS infrastructure has two services: authentication and authorization. Explain the two services.
JAAS authentication from your application typically involves the steps. Explain the steps...........

Write your comment - Share Knowledge and Experience

Discussion Board
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 02:39 AM

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 05:24 AM

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 05:23 AM

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 05:22 AM

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 05:22 AM

 

 
Interview questions
 
Home | Want a Job? Submit Key Skills | Employer login | My key skills | About us | Sitemap | Contact us