Java Interview Questions ans Answers:

Posted by

Before going for any company interview related to Core Java and Java OOPS concepts, if you go through the following Java Interview Questions and Answers then chances of being selected and coverage of your topics related to the Core Java as well as Java OOPS Concepts is very high. These Core Java Interview Questions and Answers and OOPS are based on the interview experience of the candidates. Also, Core Java Interview Questions and Answers and also OOPS based Java Interview Questions have very high accuracy of being as Interview Questions. These Java Interview questions and answers are categorized as per the Core Java Topics as follows:

OOPS Based Java Interview Questions and Answers

In this sections we will discuss about various OOPS Concept Based Java Interview Questions and Answers:

Q.1.What are the principle concepts of OOPS?
Ans: There are four principle concepts upon which object oriented design and OOPS programming Java rest which are listed as:

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation
    (i.e. easily remember as A-PIE).

Q.2.What is Abstraction?
Ans: Abstraction is Java OOPS concept that refers to the act of representing essential features without including the background details or the explanations.

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

Q.4.What is the difference between abstraction and encapsulation?
Ans: There are various differences between abstraction and encapsulation and some of the important are listed as follows:

  •  The abstraction focuses on the outside view of an object (i.e. the interface) where as the encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
  • Encapsulation is the implementation while abstraction solves the problem in the design side.
  •  Encapsulation is the deliverable of the abstraction.
  • Encapsulation barely talks about grouping up your abstraction to fit into the developer needs.

Q.5.What is Inheritance?
Ans: In Java OOPS, 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 or a parent class in Java.
  •  The class that does the inheritance of the other class is called a subclass of that class.
  • Inheritance is done by using the keyword extends in Java.
  • The two most common reasons to use the process of inheritance in Java are:
    -To promote the code reuse
    -To use the polymorphism

In the above section we discussed about various OOPS concept Based Java Interview Questions and Answers. In the next section we will discuss some important Polymorphism Based Java Interview Questions and Answers.

Polymorphism Based Java Interview Questions and Answers:

In this sections we will discuss about various Polymorphism Concept Based Java Interview Questions and Answers:

Q.6.What is Polymorphism?
Ans: Polymorphism is simply described as “one interface, many implementations.” Polymorphism is a characteristics of being able to assign a different meaning or different usage to something and that too in different contexts. This is used to allow an entity such as a variable, a function, or an object to have more than one form.

Q.7.How does Java implement polymorphism?
Ans: To achieve Polymorphism in java, Inheritance, Overloading and Overriding are used.
Polymorphism manifests itself in Java in the form of multiple methods having same names.

  • In some of the cases in Java, multiple methods have the same name but different formal argument lists known as the overloaded methods.
  • In other cases of Java, multiple methods have the same name, same return type, and same formal argument list known as the overridden methods.

Q.8.Explain the different types of Polymorphism.
Ans: There are two types of polymorphism in Java:

  • Compile time polymorphism
  • Run time polymorphism. 

Compile time polymorphism is method overloading where as the Runtime polymorphism is achieved using inheritance and the interface.

Note:

  • Method overloading : from a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
  • Method overriding through inheritance
  • Method overriding through the Java interface

Q.9.What is runtime polymorphism or dynamic method dispatch in Java?
Ans: In Java, runtime polymorphism or the dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at the compile time. In this process, the overridden method is called through the reference variable of a superclass. The determination of the method,that is to be called, is based up on the object being referred to by the reference variable.

Q.10.What is Dynamic Binding?
Ans: In Core Java, the term “Binding” refers to the linking up of a procedure call to the code to be executed in response to the call.
Dynamic binding is the procedure in which the code associated with a given procedure call is not known until the time of the call at run-time. Dynamic binding is associated with polymorphism and inheritance. This is also known as late binding.

Q.11.What is method overloading?
Ans: Method Overloading means to have two or more than two methods with the same name in the same class with different arguments.

The important benefit of the method overloading is:
It allows you to implement the methods that support the same semantic operation but differ by number of arguments or the argument type.

Note:
In Java, all the overloaded methods:

  • MUST change the argument list
  • CAN change the return type
  • CAN change the access modifier
  • CAN declare new or broader checked exceptions
  • Any method can be overloaded in the same class or in a subclass.

Q.12.What is method overriding?
Ans: Method overriding occurs when sub class declares a method that has the same type of arguments as a method declared by one of its superclass. The important benefit of overriding is the ability to define a behavior that’s specific to a particular subclass type.

Note: In Java method overriding process:

  • The overriding method must not have a more restrictive access modifier than the method
    being overridden. For example, you can’t override a method which is marked as public and cannot make it as protected.
  • Final method can not be override.
  • Static method can not be override.

Q.13.Differentiate between method overloading and method overriding.
Ans:  Overloaded Method:

  • Arguments must change
  • Return type can change
  • Return exceptions can change, reduce or eliminate.
  • Access can change
  • Invocation Reference type: It determines which overloaded version is selected.
  • Object type: determines which method is selected. Happens at runtime.

Overridden Method:

  • Arguments must  not change
  • Return type can’t change except for covariant
  • Must not throw new or broader checked exceptions
  • Must not make access more restrictive (can be less restrictive)
  • Invocation Reference type: It happens at compile time.
  • Object type: happens at runtime.

Q.14.Can overloaded methods be overridden too?
Ans: Yes, the derived classes still can override the overloaded methods. Polymorphism will still happen. Also, the compiler will not bind the method calls as it’s overloaded, because it might be overridden now or in the future.

Q.15.Is it possible to override the main method in Java?
Ans: No, it is not possible to override the main method in Java because main method is a static method and a static method can not  be overridden in Java.

Q.16.How to invoke a superclass version of an Overridden method?
Ans: To invoke a superclass method that has been overridden in a subclass, you can either call the method directly through a superclass instance, or you can use the “super” prefix in the subclass itself. From the point of the view of the subclass, the super keyword provides an explicit reference to the superclass’ implementation of the method.

// From subclass
super.overriddenMethod();

Q.17.What is Super?
Ans: Super is a keyword that is used to access the method or the member variables from the superclass.
If a method hides one of the member variables in its superclass, the method can have the reference  to the hidden member variable through the use of the Super keyword. Similarly, if a method overrides one of the methods in its superclass, the method can invoke the overridden method by making use of the Super keyword.
Note:

  • You can only go back by one level.
  • In the constructor, if you use super() then, it must be the very first code, and you can not access any this.xxx variables or the methods to compute its parameters.

Q.18.How do you prevent a method from being overridden?
Ans: In order to prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration meaning as “this is the final implementation of this method”. This also means the end of its inheritance hierarchy.

Syntax:

public final void exampleMethod() {
// Method statements
}

In the above section we discussed about various Polymorphism concept Based Java Interview Questions and Answers. In the next section we will discuss some important Interface Based Java Interview Questions and Answers.

Interface Based Java Interview Questions and Answers

In this sections we will discuss about various Interface Based Java Interview Questions and Answers:

Q.19.What is an Interface?
Ans: An interface is a description of a set of methods which the conforming implementing classes must have.
Note:

  • You can not mark an interface as final.
  • Interface variables must be declared as static.
  • An Interface cannot extend anything but can extend another interfaces.

Q.20.Can we instantiate an interface?
Ans: No, you can not instantiate an interface directly, but you can instantiate a class that implements an Interface.

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

Q.22.Do interfaces have member variables?
Ans: Interfaces may or may not have member variables, but these member variables are implicitly public, static, and final. In other words, interfaces can declare only the constants, can not instance variables that are available to all implementations and may be used as a key references for method arguments.

Q.23.Which modifiers are allowed in an Interface for methods?
Ans: For methods in interfaces, only public and abstract modifiers are allowed.

Q.24.What is a marker interface?
Ans: Marker interfaces are those that do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are the typical marker interfaces. These interfaces do not contain any methods, but classes must implement this interface in order to be serialized and deserialized.

In the above section we discussed about various Interface Based Java Interview Questions and Answers. In the next section we will discuss some important Abstract Class Based Java Interview Questions and Answers.

Abstract Class Based Java Interview Questions and Answers

Q.25.What is an abstract class?
Ans: Abstract classes are classes which contain one or more abstract methods. An abstract method is a method which is declared, but it does not contain implementation.
Note:

  • If even a single method is abstract, the whole class must be declared as abstract.
  •  Abstract classes may not be instantiated, and require other subclasses to provide the implementations for the abstract methods.
  • You can not mark a class as abstract and final both.

Q.26.Can we instantiate an abstract class in Java?
Ans: No, we can never instantiate an abstract class. Its sole purpose is to be extended by the subclasses.

Q.27.What are the differences between Interface and Abstract class?
Ans: There are various differences between the Interface and the Abstract class of Java that are listed as follows:
Abstract Class: 

  • An abstract class can provide complete, default code and may be just the details that have to be overridden.
  • In case of this class, a class may extend only one abstract class at a time. 
  • This class may have non-abstract methods. 
  • This class may have instance variables. 
  • This class may have any visibility which may be public, private or protected.
  • If a new method is added to an abstract class then we have the option of providing the default implementation and therefore, all the already existing code might work properly.
  • It can contain constructors.
  • These classes are very fast. 

Interfaces:

  • An interface can not provide any code at all but can provide just the signature.
  • A single class may implement several interfaces.
  • All methods of an Interface are abstract.
  • An Interface cannot have instance variables.
  • An Interface visibility must be public (or) none.
  • If we add a new method to an Interface then we will have to track down all of the implementations of the interface and we need to define implementation for the new method.
  • An Interface cannot contain constructors .
  • Interfaces are slow as they require extra indirection to find the corresponding method in the actual class.

Q.28.When should I use abstract classes and when should I use interfaces in Java?
Ans: In Java, make use of Interfaces when:

  • You find that something in your created design will change frequently.
  • If various implementations only share the method signatures then it is better to make use of Interfaces.
  • When you need some classes to use an some methods which you don’t want to be included in the class, then you must go for the interface, which makes it easy to just implement and use the methods defined in the interface.

Use Abstract Class when:

  • If various implementations are of the same kind and also use common behavior or the status then its better to use the abstract class.
  • If you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass then use abstract class.
  • Abstract classes are an excellent way to create the planned inheritance hierarchies as well as they’re also a good choice for non-leaf classes in class hierarchies.

Q.29.When you declare a method as abstract, can other non-abstract methods access it?
Ans: Yes, the other non-abstract methods can access a method that you declared as the abstract.

Q.30.Can there be an abstract class with no abstract methods declared in it?
Ans:Yes, there can be an abstract class without any abstract methods declared in it.

Constructor Based Java Interview Questions and Answers

Q.31.What is Constructor?
Ans: Constructor:

  • A constructor is a type of special method whose task is to initialize the object of the class.
  • It is special as its name is same as the class name.
  • It doesn’t have return type, not even void and therefore they can not return values.
  • It can not be inherited by the derived class, though a derived class can call the base class constructor.
  • This is invoked whenever an object of its associated class gets created.
    Read more about Constructor.

Q.32.How does the Java default constructor be provided?
Ans: If a class defined by the code does not have any constructor then, compiler will automatically provide one no-parameter-constructor (default-constructor in Java) for the class in the byte code. The access modifiers (public/private/default/protected provided by Java) of the default constructor is the same as the class itself.

Q.33.Can constructor be inherited?
Ans:No, constructor can not be inherited but a derived class can call the base class constructor.

Q.34.What are the differences between Constructors and Methods?
Ans:
Constructors: 

  • Purpose is to create an instance of a class
  • Modifiers can’t be abstract, final, native, static, or synchronized
  • Has no return type, not even void
  • Name of the constructors is same as the name of the class (first letter in any name, except the class or method, is capitalized by convention) – is usually a noun
  • this keyword refers to another constructor in the same class. If it is used then it must be the first line of the constructor
  • super keyword calls the constructor of the parent the class. If it is used then it must be the first line of the constructor
  • Inheritance in Constructors: They are not inherited

Methods:

  • Purpose is to group Java statements
  • For methods, access modifiers can be abstract, final, native, static, or synchronized
  • Has void or a valid return type
  • The names of the methods start with a lowercase letter by convention – is usually the name of an action
  • this keyword refers to an instance of the owning class and can’t be used by the static methods.
  • super keyword calls an overridden method present in the parent class
  • Inheritance in Methods: They are inherited

Q.35.How are this() and super() used with constructors?
Ans:

  • Constructors use this keyword to refer to the other constructor in the same class having a different parameter list.
  • Constructors use super keyword to invoke the constructor of the superclass. If a constructor uses the super keyword then, it must use super keyword in the first line otherwise, the compiler will complain about it.

Q.36.What are the differences between Class Methods and Instance Methods?
Ans:
Class Methods:

  • These are the methods which are declared as static. Also, these methods can be called without creating an instance of the class (means without instantiation).
  • These are the methods that can only operate on the class members and not on the instance members as the class methods are unaware of the instance members.
  • Class methods are the methods which are declared as static and these methods can be called without creating an instance of the class so no instantiation is required.

Instance Methods:

  • On the other hand, the requirement of these methods is that they need an instance of the class to exist before they can be called so an instance of the class needs to be created by the use of the new keyword (means instantiation of the class is needed). These methods operate on specific instances of the classes.
  • The instance methods of the class can not be called from within a class method unless these instance methods are being called on an instance of that particular class.
  • The instance methods are not declared as static so instantiation is needed.

Q.37.How are this() and super() used with constructors?
Ans:

  • Constructors use this() to refer to the other constructor within the same class having a different parameter list.
  • Constructors use super() to invoke the constructor of the superclass. If a constructor uses super() then, it must use super() in the first line otherwise, the compiler will complain about it.

Access Specifiers Based Java Interview Questions and Answers

Q.38.What are Access Specifiers in Java?
Ans: Encapsulation is one of the techniques in the object-oriented programming (OOPS) in java which concerns the hiding of the data in a class and making this class available only through the methods. Java allows you to control the access to the classes, methods and fields via access specifiers.

Q.39.What are Access Specifiers available in Java?
Ans: Java offers the four access specifiers (public, protected, default, private) and these java access specifiers are listed below in the decreasing accessibility order:

  • Public Access Specifier: 
    All the public classes, methods, and fields can be accessed from everywhere.
  • Protected Access Specifier: 
    All the protected methods and fields can only be accessed within the same class to which these methods and fields belong, also within its subclasses, and within classes of the same package as well.
  • Default Access Specifier(no specifier):
    If you do not set access to any of the specific levels, then such classes, methods, or fields will be accessible from inside the same package to which the classes, methods, or fields belong, but not from the outside of this package.
  • Private Access Specifier: 
    All the private methods and fields can only be accessed within the same class to which these methods and the fields belong. All the private methods and fields are not visible within the subclasses and are not inherited by subclasses.

Situation: 

Accessibility to the class from the same package? 
public : yes 
protected : yes 
default : yes 
private : no

Accessibility to the class from different package?
public : yes 
protected : no, unless it is a subclass 
default : no
private : no

Q.40.What is final modifier?
Ans: In java, the final modifier is a keyword which makes sure that the programmer cannot change the value anymore. The actual meaning of the final modifier depends on where it is applied, whether it is applied to a class, a variable, or a method.

  • final Classes: The final classes cannot have their subclasses.
  • final Variables: The final variables cannot be changed once they are initialized.
  • final Methods: The final methods cannot be overridden by their subclasses.

Q.41.What are the uses of final method?
Ans: There are mainly two reasons behind marking a method as final in java are:

  • final keyword disallows the subclasses to change the meaning of the method.
  • final keyword increases efficiency by allowing the compiler to turn calls to the method into the inline Java code.

Static Keyword Based Java Interview Questions and Answers

Q.42.What is static block?
Ans: Static block is a block that is executed exactly once when the class is first loaded into JVM (Java Virtual Machine). The static block will execute before going to the main method.

Q.43.What are static variables?
Ans: The variables for which there exists only one copy per class are known as static variables. These static variables are not particularly attached to an instance of a class but rather belong to a class as a whole. The declaration of these static variables is done with the help of using the static keyword as a modifier.

static type varIdentifier;

In the above java syntax, varIdentifier is the name of the variable and type is its data type.

Q.44.What is the difference between static and non-static variables?
Ans: Variables that are declared as the Static variables are not explicitly initialized in the code and they are automatically initialized with a default value. And, this default value depends on the data type of the variables.
The static variables are the variables that are associated with the class as a whole rather than associated with the specific instances of the class whereas the Non-static variables take only the unique values with each object instance.

Q.45.What are static methods?
Ans: The methods that are declared with the keyword static as a modifier are called static methods or known as the class methods. They are called so because they affect a class as a whole, not only a particular instance of the class. These Static methods are always invoked without reference to a particular instance of a class.

Note:

  • The static methods can only call the other static methods.
  • The use of a static method suffers from the following listed restrictions:
  • A static method must only access the static data.
  • A static method can’t reference to the current object with the use of super or this keywords.

Collections Based Java Interview Questions

Iterator Based Java Interview Questions and Answers

Q.46.What is an Iterator ?
Ans:

  • The is an interface which is helpful as well as used to step through all the elements of a Collection in Java.
  • Iterators let you to process each element of a Collection.
  • Iterators are a generic way to go through all the elements of a Collection no matter how the collection is organized. Iterator is an Interface implemented in a different way for each and every Collection in java.

Q.47.How do you traverse through a collection using its Iterator?
Ans: To make use of an iterator for traversing through the contents of a collection we follow the following steps:

  • To start with the iterator, obtain an iterator of the collection by calling the collection’s iterator() method.
  • Set up a loop that makes a call to hasNext() function then, let the loop iterate as long as hasNext() returns true.
  • Within the loop, by calling next() obtain each element of the Collection in java.

Q.48.How do you remove elements during Iteration in Java?
Ans: Iterator also has a method called remove() method. When this remove() method is called then, the current element in the iteration is deleted.

Q.49.What is the difference between Enumeration and Iterator?
Ans: 
Enumeration:

  • It doesn’t have a remove() method
  • Enumeration acts as Read-only interface because it has the methods only to traverse as well as fetch the objects

Iterator:

  • It has a remove() method
  • It can be abstract, final, static, native, or synchronized

Note: 
So we use enumeration whenever we want to make Collection objects as Read-only.

Q.50.How is ListIterator?
Ans: In Java, ListIterator is just like the Iterator, except that this listIterator allows us to access the collection in either the forward direction or backward direction and allows us to modify an element.

Interface Based Java Interview Questions and Answers

Q.51.What is the List interface?
Ans: The List interface is an interface which:

  • provides support for ordered collections of the objects.
  • may contain duplicate elements as well.

Q.52.What are the main implementations of the List interface ?
Ans: The main implementations of the List interface in java are listed as follows :

  • ArrayList: It provides the resizable-array implementation of the List interface. This is the best implementation of the List interface all-around.
  • Vector: It provides the synchronized resizable-array implementation of the List interface along with some additional “legacy methods.”
  • LinkedList: This provides the doubly-linked list implementation of the List interface. This may provide better performance than the ArrayList implementation of the List Interface if elements are frequently inserted or deleted within the list. This is very much useful for queues and double-ended queues known as deques.

Q.53.What are the advantages of ArrayList over arrays?
Ans: Some of the main advantages that ArrayList has over arrays in java are:

  • This can grow dynamically
  • There are more powerful insertion and search mechanisms provided by ArrayList than arrays.

Q.54.Difference between ArrayList and Vector?
Ans: 
ArrayList: 

  • Is noy synchronized by default.
  • can only use Iterator to access the elements of the collections.
  • increases its array size by 50% if it runs out of size.
  • There is no default size for ArrayList.

Vector:

  • This is synchronized by default.
  • can use Iterator as well as Enumeration Interface to access the elements.
  • defaults to doubling the size of its array if it runs out of size
  • There is a default size of 10 for Vector.

Q.55.How to obtain Array from an ArrayList in Java?
Ans: Array can be obtained from an ArrayList using toArray() method on the ArrayList in Java.

Java

Q.56.Why insertion and deletion in ArrayList is slow compared to LinkedList ?
Ans:

  • ArrayList internally uses arrays to store its elements. When that array is filled by inserting elements then, a new array of roughly 1.5 times the size of the original array is created. After the creation of the new array, all the data of old array is copied to the new array.
  • During deletion process, all the elements that are present in the array after the deleted elements have to be moved one step back to fill up the space created by deletion of the elements. In linked list, the data is stored in nodes that have reference to its previous node and its next node. So, adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer to the newly created node. Deletion process in linked list is fast because it involves only updating the next pointer of the node before the deleted node and updating the previous pointer of the node after the deleted node.

Q.57.Why are Iterators returned by ArrayList called Fail Fast ?
Ans: The iterators returned by ArrayList are called Fail Fast because if list is structurally modified at any time after the creation of the iterator, in any way except through the iterator’s own remove or add methods, the iterator will throw an exception namely, ConcurrentModificationException in java. So,in this stage of concurrent modification, the iterator will fail so quickly and cleanly that is Fails Fastly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Q.58.How do you decide when to use ArrayList and when to use LinkedList?
Ans: In Java Collections, to decide when to use ArrayList and when to use LinkedList:

If you need to support random access, without the insertion or removal of elements from any place other than the end, then ArrayList provides the optimal collection. If, however, you are required to add and remove elements frequently from the mid of the list and want to only access the list elements sequentially, then LinkedList provides the better implementation.

Q.59.What is the Set interface?
Ans:

  • The Set interface offers you various methods to access the elements present in a finite mathematical set
  • Set does not allow the duplicate elements
  • Set contains no methods other than those inherited from Collection itself
  • It sets the restriction that duplicate elements are not allowed.
  • Two set objects are equal only if they contain the same elements

Q.60.What are the main Implementations of the Set interface?
Ans: The main implementations of the Set interface are as follows:

  • Using HashSet
  • Using TreeSet
  • Using LinkedHashSet
  • Using EnumSet

Q.61.What is a HashSet ?
Ans:

  • A HashSet is a type of unsorted and unordered Set.
  • This uses the hashcode of the object that is being inserted. So the more efficient is your hashcode() implementation, the better access performance you’ll get.
  • Use this class when you want a collection with no duplicate values and you don’t care about the order when you iterate through the collection.

Q.62.What is a TreeSet?
Ans: TreeSet is a kind of Set implementation that keeps the elements in the sorted order. These elements are sorted according to the element’s natural order or by the comparator provided at the time of creation.

Q.63.What is an EnumSet?
Ans: An EnumSet is a very specialized set to use with enum types, all of the elements in the EnumSet type which is specified, implicitly or explicitly, when the set is created.

Q.64.Difference between HashSet and TreeSet in Java Collection?
Ans:
HashSet: 

  • HashSet is under set interface. That means it does not guarantee for either sorted order or sequential order.
  • Any type of elements can be added to hash set.

TreeSet:

  • TreeSet is under set which means it provides elements in a sorted order (ascending order).
  • Only similar types of elements can be added to tree set.

Map Based Java Interview Questions and Answers

Q.65.What is a Map?
Ans:
In Java Collections, Map is defined as:

  • A map is an object that stores associations between the keys and the values means stores key/value pairs.
  • When a key is given, you can find its value. Key and value are objects.
  • All the keys must be unique, but the values can be duplicated.
  • Some of the maps may accept a null key and null value, others can not accept.

Q.66.What are the main Implementations of the Map interface in Java?
Ans: The main implementations of the Map interface in java are as follows:

  • Using HashMap
  • Using HashTable
  • Using TreeMap
  • Using EnumMap

Q.67.What is a TreeMap?
Ans: In Java Collections, TreeMap actually implements the SortedMap interface that further 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 the time of creation. TreeMap is based on the RB tree data structure (Red-Black tree).

Q.68.How will you decide when to use HashMap and when to use TreeMap?
Ans: In Java Collections, 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. It may be faster to add elements to a HashMap depending upon the size of your collection, then convert the map to a TreeMap for sorted key traversal.

Q.69.Difference between HashMap and Hashtable ?
Ans:

HashMap: 

  • HashMap allows you to have null values as well as one null key.
  • The iterator in the HashMap is fail-safe means if you change the map while iterating then you’ll know.
  • HashMap is not synchronized.

Hashtable:

  • HashTable does not allow you to have null values as key and value.
  • The enumerator for the Hashtables is not fail-safe.
  • Hashtable is synchronized.

Note: In Java, only one NULL is allowed as a key in the HashMap. HashMap does not allow you to have multiple keys to be NULL but it can have multiple NULL values.

Q.70.How does a Hashtable internally maintain the key-value pairs in java Collections?
Ans: TreeMap actually implements the SortedMap interface that further 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 the time of creation. TreeMap is based on the RB tree data structure (Red-Black tree).

View Based Java Interview Questions and Answers

Q.71.What Are the different Collection Views That Maps Provide?
Ans: In Core Java, the Maps Provide Three Collection Views which are listed as follows:

  • Key Set: It allows a map’s content to be viewed as a set of keys.
  • Values Collection: It allows a map’s contents to be viewed as a set of values.
  • Entry Set: It allows a map’s contents to be viewed as a set of key-value pairs or mappings.

Q.72.What is a KeySet View ?
Ans: KeySet is a set that is returned by the keySet() method of the Map Interface. It’s a set that contains all the keys that are present in the Map.

Q.73.What is a Values Collection View?
Ans: A Values Collection View is a type of collection that is returned by the values() method of the Map Interface. A Values Collection contains all the objects present as values in the map.

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

Q.75.How do you sort an ArrayList (or any list) of user-defined objects?
Ans:In order to sort an ArrayList (or any list) of user defined objects, we will create an implementation of the java.lang.Comparable interface which knows how to order your objects and pass them to java.util.Collections.sort(List, Comparator).

Comparable and Comparator Interface Based Java Interview Questions and Answers:

Q.76.What is the Comparable interface?
Ans: The Comparable interface is used for sorting the collections and arrays of objects using the Collections.sort() method and java.utils.Arrays.sort() methods respectively. The objects of the class that is implementing the Comparable interface can also be ordered. The Comparable interface in the general form is written as:

interface Comparable<T>
where T represents the name of the type parameter.

All the classes that implements the Comparable interface must implement the compareTo() method as well that has the return type as an integer. 

The signature of the compareTo() method is shown as follows:
int i = obj1.compareTo(obj2)

• If obj1 < obj2: The value of i returned will be -ve.

•If obj1 > obj2: The value of i returned will be +ve.

• If obj1 = obj2: The value of i returned will be 0.

Q.77.What are the differences between the Comparable and Comparator interfaces?
Ans:
Comparable: 

  • It uses the compareTo() method.
    int object1.compareTo(object2)
  • It is necessary for you to modify the class whose instance is going to be sorted.
  • Only a single sorted sequence can be created.
  • It is used by the API classes frequently.

Comparator:

  • it uses the compare() method. int compare(Obj1, Obj2)
  • We can create a separate class in order to sort the instances.
  • Many sorted sequences can be created.
  • It used by third-party classes for sorting the instances.

Q.78.Difference between HashMap and HashTable? Can we make hashmap synchronized in Java Collections?
Ans:

1. The HashMap class is roughly equivalent to Hashtable, except that it’s unsynchronized and allows nulls. (HashMap permits null values as key and value whereas Hashtable doesn’t permit nulls).

2. HashMap doesn’t guarantee that the order of the map will be constant over the time.

3. HashMap is unsynchronized while Hashtable is synchronized.

4. Iterator within the HashMap is fail-safe while  the enumerator for the Hashtable isn’t fail-safe.

Q.79.What is the difference between set and list?
Ans: A Set stores elements in an unordered manner and doesn’t contain duplicate elements,
whereas a list stores elements in an ordered manner however could contain duplicate elements.

All the above Java Interview Questions and Answers are covering complete Core Java topics as well as OOPS Concepts that are asked in Java Interviews for freshers as well as the experienced candidates based on the core concepts of Java.

Read for RxJava and Kubernetes Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *