Java Core Interview
Java Core Interview
● 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.
Similarities:
● Neither Abstract classes or Interface can be instantiated.
● Miscellaneous features, including performance hints, the use of character streams, full precision for
java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp
values.
● Protected
● Private
● Defaults
Question: Describe the wrapper classes in Java.
Answer: 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
● Polymorphism
● Inheritance
● Encapsulation
(i.e. easily remembered as A-PIE).
2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details or
explanations.
3.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.
● Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your
abstraction to suit the developer needs.
5.What is Inheritance?
● Inheritance is the process by which objects of one class acquire the properties of objects of another class.
6.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.
13.What are the differences between method overloading and method overriding?
Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for covariant returns
Exceptions Can change Can reduce or eliminate. Must not throw new or
broader checked exceptions
Access Can change Must not make more restrictive (can be less
restrictive)
Invocation Reference type determines which Object type determines which method is selected.
overloaded version is selected. Happens at runtime.
Happens at compile time.
17.What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides
one of the member variables in its superclass, the method can refer to the hidden variable through the use of the
super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can
invoke the overridden method through the use of the super keyword.
Note:
● You can only go back one level.
● In the constructor, if you use super(), it must be the very first code, and you cannot access
any this.xxx variables or methods to compute its parameters.
19.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.
● 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.
28.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 nonleaf classes in class hierarchies.
29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.
31.What is Constructor?
● A constructor is a special method whose task is to initialize the object of its class.
● They do not have return types, not even void and therefore they cannot return values.
● They cannot be inherited, though a derived class can call the base class constructor.
● Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in
the first line; otherwise, the compiler will complain.
36.What are the differences between Class Methods and Instance Methods?
Class Methods Instance Methods
Instance methods on the other hand require an instance of the
Class methods are methods which are declared as static.
class to exist before they can be called, so an instance of a
The method can be called without creating an instance of
class needs to be created by using the new keyword.
the class
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not Instance methods of the class can also not be called from
on instance members as class methods are unaware of within a class method unless they are being called on an
instance members. instance of that class.
Class methods are methods which are declared as static.
The method can be called without creating an instance of Instance methods are not declared as static.
the class.
● Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in
the first line; otherwise, the compiler will complain.
● Protected- protected methods and fields can only be accessed within the same class to which the
methods and fields belong, within its subclasses, and within classes of the same package.
● Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be
accessible from inside the same package to which the class, method, or field belongs, but not from
outside this package.
● Private- private methods and fields can only be accessed within the same class to which the methods and
fields belong. private methods and fields are not visible within subclasses and are not inherited by
subclasses.
● Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main
method the static block will execute.
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static
variables take on unique values with each object instance.
● A static method cannot reference to the current object using keywords super or this.
46.What is an Iterator ?
● The Iterator interface is used to step through the elements of a Collection.
● Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
50.How is ListIterator?
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward
direction and lets us modify an element
Because, if list is structurally modified at any time after the iterator is created, in any way except through the
iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the
face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-
deterministic behavior at an undetermined time in the future.
58.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.
59.What is the Set interface ?
● The Set interface provides methods for accessing the elements of a finite mathematical set
● Two Set objects are equal if they contain the same elements
60.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
● HashSet
● TreeSet
● LinkedHashSet
● EnumSet
61.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.
62.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.
63.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.
65.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.
● Some maps can accept a null key and null values, others cannot.
● HashTable
● TreeMap
● EnumMap
67.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.
68.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.
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.
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.
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.
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).
The Comparable interface is used to sort collections and arrays of objects using
the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the
Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable<T>
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return
type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
77.What are the differences between the Comparable and Comparator interfaces ?
Comparable Comparato
t uses the compare() method.
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going
A separate class can be created in order to sort the instances.
to be sorted.
Only one sort sequence can be created. Many sort sequences can be created.
It is frequently used by the API classes. It used by third-party classes to sort instances.