Core Java Interview Questions


1.    What is the most important feature of Java?
Java is a platform independent language.

2.    What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

3.    Are JVM's platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

4.    What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

5.    What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.

6.    What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Java.

7.    What is constructor?
Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation

8.    Is constructor inherited?
No, constructor is not inherited.

9.    Can you make a constructor final?
No, constructor can't be final.

10. What is static variable?
static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
static variable gets memory only once in class area at the time of class loading.

11. What is static method?
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.

12. Why main method is static?
because object is not required to call static method if It were non-static method, jvm creates object first then call main() method that will lead to the problem of extra memory allocation.

13. What is static block?
Is used to initialize the static data member.
It is executed before main method at the time of class loading.

14. What is difference between static (class) method and instance method?
static or class method:
·         A method i.e. declared as static is known as static method.
·         Object is not required to call static method.
·         Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly.
instance method:
·         A method i.e. not declared as static is known as instance method.
·         Object is required to call instance methods.
·         static and non-static variables both can be accessed in instance methods.

15. What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:
Abstraction
Polymorphism
Inheritance
Encapsulation

16. What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details or explanations.

17. What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

18. What is the difference between abstraction and encapsulation?
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

19. What is Inheritance?
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism

20. What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

21. How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

22. Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
NoteFrom a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

23. What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch 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.

24. What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (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. It is associated with polymorphism and inheritance.

25. What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.

26. What is method overriding?
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:
The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
You cannot override a method marked final
You cannot override a method marked static

27. What is an Interface?
An interface is a description of a set of methods that conforming implementing classes must have.
Note:
You can’t mark an interface as final.
Interface variables must be static.
An Interface cannot extend anything but another interfaces.

28. Can we instantiate an interface?
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

29. Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

30. Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

31. What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

32. What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.

33. What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. 
Note:
If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
You can’t mark a class as both abstract and final.

34. Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

35. When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
You see that something in your design will change frequently.
If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for non-leaf classes in class hierarchies.

36. When you declare a method as abstract, can other non-abstract methods access it?
Yes, other non-abstract methods can access a method that you declare as abstract.

37. Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.

38. What is an Iterator?
·         The Iterator interface is used to step through the elements of a Collection.
·         Iterators let you process each element of a Collection.
·         Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
·         Iterator is an Interface implemented a different way for every Collection.

39. How do you traverse through a collection using its Iterator?
  • To use an iterator to traverse through the contents of a collection, follow these steps:
  • Obtain an iterator to the start of the collection by calling the collection iterator() method.
  • Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
  • Within the loop, obtain each element by calling next().

40. How do you remove elements during Iteration?
Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

41. What is the List interface?
  • The List interface provides support for ordered collections of objects.
  • Lists may contain duplicate elements.

42. What are the main implementations of the List interface ?
The main implementations of the List interface are as follows :
  • ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
  • Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
  • LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

43. What are the advantages of ArrayList over arrays?
Some of the advantages ArrayList has over arrays are:
  • It can grow dynamically
  • It provides more powerful insertion and search mechanisms than arrays.

44. Why insertion and deletion in ArrayList is slow compared to LinkedList?
  • ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
  • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

45. How do you decide when to use ArrayList and When to use LinkedList?
·         If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

46.  What is the Set interface?

  • The Set interface provides methods for accessing the elements of a finite mathematical set
  • Sets do not allow duplicate elements
  • Contains no methods other than those inherited from Collection
  • It adds the restriction that duplicate elements are prohibited
  • Two Set objects are equal if they contain the same elements

47. What are the main Implementations of the Set interface?
The main implementations of the List interface are as follows:
  • HashSet
  • TreeSet
  • LinkedHashSet
  • EnumSet

48. What is a HashSet ?
  • A HashSet is an unsorted, unordered Set.
  • It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
  • Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.

49.  What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

50.  What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

51.  What is a Map ?

  • A map is an object that stores associations between keys and values (key/value pairs).
  • Given a key, you can find its value. Both keys  and  values are objects.
  • The keys must be unique, but the values may be duplicated.
  • Some maps can accept a null key and null values, others cannot.
52. What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
  • HashMap
  • HashTable
  • TreeMap
  • EnumMap

53.  What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.


54.  How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

55. What Are the different Collection Views That Maps Provide?
Maps Provide Three Collection Views.
  • Key Set - allow a map's contents to be viewed as a set of keys.
  • Values Collection - allow a map's contents to be viewed as a set of values.
  • Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

56.  What is a KeySet View ?
KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.

57.  What is a Values Collection View ?
Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.

58.  What is an EntrySet View ?
Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value.

59.  How do you sort an ArrayList (or any list) of user-defined objects ?
Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).


1 comment: