Do you know that? Always be professional. next

See right interview answers on 30 common job interview questions

Collapse | Expand

1. Can you access non static variable in static context ?

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

2. Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
 Following table lists the primitive types and the corresponding wrapper classes:
 Primitive Wrapper
 boolean  - java.lang.Boolean
 byte - java.lang.Byte
 char - java.lang.Character
 double - java.lang.Double
 float - java.lang.Float
 int - java.lang.Integer
 long - java.lang.Long
 short - java.lang.Short
 void - java.lang.Void

3. Explain different ways of creating a thread. Which one would you prefer and why ?

There are three ways that can be used in order for a Thread to be created:

 • A class may extend the Thread class.
        • A class may implement the Runnable interface.
        • An application can use the Executor framework, in order to create a thread pool.

The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.

4. Explain the available thread states in a high-level?

During its execution, a thread can reside in one of the following states:

  • Runnable: A thread becomes ready to run, but does not necessarily start running immediately.
         • Running: The processor is actively executing the thread code.
         • Waiting: A thread is in a blocked state waiting for some external processing to finish.
         • Sleeping: The thread is forced to sleep.
         • Blocked on I/O: Waiting for an I/O operation to complete.
         • Blocked on Synchronization: Waiting to acquire a lock.
         • Dead: The thread has finished its execution.

5. Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods". 
  From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
  * Method overloading
  * Method overriding through inheritance
  * Method overriding through the Java interface

6. How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
 Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

7. How HashMap works in Java ?

A HashMap in Java stores key-value pairs. The HashMap requires a hash function and useshashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

8. How to define an Abstract class?Describe through an exanple?

A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
  Example of Abstract class:
  abstract class testAbstractClass { 
      protected String myString; 
      public String getMyString() { 
      return myString; 
  public abstract string anyAbstractFunction();

9. How to define an Interface?Describe through an exanple?

In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
   Example of Interface:
   public interface sampleInterface {
       public void functionOne();
       public long CONSTANT_ONE = 1000;

10. How you can force the garbage collection?

Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

11. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

12. What are pass by reference and pass by value ?

When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

13. What are some advantages and disadvantages of Java Sockets?

Some advantages of Java Sockets: 
   Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
   Some disadvantages of Java Sockets:
   Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network   Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

14. What are the basic interfaces of Java Collections Framework ?

Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:

• Collection, which represents a group of objects known as its elements.
       • Set, which is a collection that cannot contain duplicate elements.
       • List, which is an ordered collection and can contain duplicate elements.
       • Map, which is an object that maps keys to values and cannot contain duplicate keys.

15. What are the Data Types supported by Java ? What is Autoboxing and Unboxing ?

The eight primitive data types supported by the Java programming language are:

   • byte
          • short
          • int
          • long
          • float
          • double
          • boolean
          • char

Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. For example, the compiler converts an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this operation is called unboxing.

16. What are Transient and Volatile Modifiers?


The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.


Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

17. What differences exist between HashMap and Hashtable ?

Both the HashMap and Hashtable classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:

 • A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow neither null keys, nor null values.
        • A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while aHashtable is suitable for multi-threaded environments.
        • A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, aHashtable provides an Enumeration of its keys.
        • The Hashtable class is considered to be a legacy class.

18. What do you understand by Synchronization?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
   E.g. Synchronizing a function:
   public synchronized void Method1 () {
       // Appropriate method-related code. 
   E.g. Synchronizing a block of code inside a function:
   public myFunction (){
       synchronized (this) { 
       // Synchronized code here.

19. What does the static keyword mean ? Can you override private or static method in Java ?

The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot overridestatic methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable.

20. What is a Constructor, Constructor Overloading in Java and Copy-Constructor ?

A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

21. What is Collection API?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
   Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
   Example of interfaces: Collection, Set, List and Map.

22. What is difference between Array and ArrayList ? When will you use Array over ArrayList ?

The Array and ArrayListclasses differ on the following features:

  • Arrays can contain primitive or objects, while an ArrayList can contain only objects.
         • Arrays have fixed size, while an ArrayList is dynamic.
         • An ArrayListprovides more methods and features, such as addAll, removeAll, iterator, etc.
         • For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.

23. What is difference between ArrayList and LinkedList ?

Both the ArrayList and LinkedList classes implement the List interface, but they differ on the following features:

 • An ArrayList is an index based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1). On the other hand, a LinkedList stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n).
        • The Insertion, addition and removal operations of an element are faster in a LinkedList compared to an ArrayList, because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection.
        • A LinkedList consumes more memory than an ArrayList, because every node in a LinkedList stores two references, one for its previous element and one for its next element.

24. What is difference between overloading and overriding?

a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.

  b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. 

 c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass.

  d) Overloading must have different method signatures whereas overriding must have same signature.

25. What is final, finalize() and finally?

final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

26. What is Function Overriding and Overloading in Java ?

Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

27. What is JVM ? Why is Java called the Platform Independent Programming Language ?

A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by the JVM. Java was designed to allow application programs to be built that could be run on any platform, without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible, because it is aware of the specific instruction lengths and other particularities of the underlying hardware platform.

28. What is RMI ?

The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object.

29. What is structure of Java Heap ? What is Perm Gen space in Heap ?

The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

30. What is the difference between an Interface and an Abstract class ?

Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features:

   • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
          • A class may implement a number of Interfaces, but can extend only one abstract class.
          • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
          • Abstract classes can implement interfaces without even providing the implementation of interface methods.
          • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
          • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
          • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

31. What is the difference between Enumeration and Iterator interfaces ?

Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iteratorsallow the caller to remove elements from the underlying collection, something which is not possible with Enumerations.

32. What is the difference between Integer and int?

a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. 

 b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

33. What is the Difference between JDK and JRE ?

The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being executed. It also includes browser plugins for applet execution. The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.

34. What is the difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables.
  Public: accessible to all classes
  Private: accessible only to the class to which they belong
  Protected: accessible to the class to which they belong and any subclasses.
  Access specifiers are keywords that determines the type of access to the member of a class. These are:
  * Public
  * Protected
  * Private
  * Defaults

35. What is the importance of hashCode() and equals() methods ?

A HashMap in Java uses the hashCode and equals methods to determine the index of the key-value pair. These methods are also used when we request the value of a specific key. If these methods are not implemented correctly, two different keys might produce the same hash value and thus, will be considered as equal by the collection. Furthermore, these methods are also used to detect duplicates. Thus, the implementation of both methods is crucial to the accuracy and correctness of the HashMap.

36. What's the difference between an interface and an abstract class? Also discuss the similarities.

Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
  Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
  Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
  Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.
  Differences are as follows:
  * Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  * Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  * A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  * Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 
  * Neither Abstract classes or Interface can be instantiated.

37. What's the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

38. Why Collection doesn?t extend Cloneable and Serializable interfaces ?

The Collection interface specifies groups of objects known as elements. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements. Some collections allow duplicate keys, while some other collections don’t. The semantics and the implications of either cloning or serialization come into play when dealing with actual implementations. Thus, the concrete implementations of collections should decide how they can be cloned or serialized.