Here is a list of the most asked java interview questions for software engineers. I have kept the answers short so that this compilation can be handy during last-minute brush-up.
I would love to hear your feedback regarding this list, do leave your suggestions and comments.
1. Why Dimond problem does not occur with default method implementation in Java 8?
A. From Java 8, default methods are introduced and since then we can inherit from multiple interfaces. This creates a conflict if a default method in 2 different interfaces or a combination of classes and interface has the same signature.
To resolve this conflict following rules are laid down in Java 8 -
- A class will have greater priority over interfaces during conflict resolution. This means if a sub-class extending from class and interface finds a conflicting method common to both parents the method inside the class will be run during run time.
- Sub interface takes higher priority than the parent interface. Imagine a three-level inheritance where C extends B extends A, where C is a concrete class and A and B are interfaces that have a method with a common signature and a default implementation, then at run time method inside B will be executed when called from C, provided C has not overridden it.
- In the case of a classic diamond scenario, where interface B extends interface A, interface C extends A, and class D extends both B and C, there arise three variations. First that the method has a default implementation in A which is the highest parent and no overriding in either of the children. In this case implementation inside A will execute without any conflict
- Secondly if one of the children of A ie. either B or C overrides a shared method from A, then the implementation inside the sub-class will be called at run time.
- Thirdly if both B and C override the common method from A then D is left with no other alternative but to specify its own implementation of that method.
2 . How to create an immutable object
A. To create an immutable class in java, you have to do the following steps.
a. Declare the class as final so it can’t be extended.
b. Make all fields private so that direct access is not allowed.
c. Don’t provide setter methods for variables
d. Make all mutable fields final so that their values can be assigned only once.
e. Initialize all the fields via a constructor performing the deep copy.
f. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
3. What is a volatile variable
A. Volatile variables are stored in the main memory and no cache is maintained for them. All reads and writes happen directly from and to the main memory. Main memory is visible to all threads in the application hence all threads share the same volatile variable value. Access to the volatile is automatically synchronized. So JVM ensures an ordering while reading/writing to the variable.
Hence volatile variables are thread-safe. However non-atomic
operations like increment and decrement are not thread-safe.
4. How to create a shallow copy of objects?
A. Shallow copy of an object can be created by cloning. This is achieved by implementing a cloneable interface and calling the clone method.
5. How to create a deep copy of objects?
A. There are multiple methods to perform a deep copy
4. How to create a shallow copy of objects?
A. Shallow copy of an object can be created by cloning. This is achieved by implementing a cloneable interface and calling the clone method.
5. How to create a deep copy of objects?
A. There are multiple methods to perform a deep copy
a. By
writing copy constructors
b.
Manually Cloning (need to override clone method and mark objects
cloneable)
b. By
Serialization (need to mark objects serializable)
c. By Json
serialization using Gson or Jackson (can be used without any
prerequisite)
6. How to return value from a thread?
A. By implementing a callable interface instead of the runnable interface in a thread.
Using special for loop:
6. How to return value from a thread?
A. By implementing a callable interface instead of the runnable interface in a thread.
7. How to iterate on a list using
a. Java 8
b. special for loop
c. normal for loop
d iterators?
A.In java 8 we can loop using the for each method and lambda expression on collections in the following way :
a. Java 8
b. special for loop
c. normal for loop
d iterators?
A.In java 8 we can loop using the for each method and lambda expression on collections in the following way :
List<String> list = new ArrayList<>();
list.foreach(System.out::println);
Using special for loop:
for(dataType item : array) {
...
}
for(int i=0; i< arr.length-1; i++) {
...
}
8. Difference Between iterator and list iterator?
A.
A.
a. Direction: Basic Iterator can traverse the elements in a collection only
in the forward direction. ListIterator can traverse the elements in a
collection in the forward as well as the backward direction.
b. Add: Basic Iterator Iterator is unable to add elements to a
collection. ListIteror can add elements to a collection.
c. Modify: Basic Iterator Iterator can not modify the elements in a
collection. ListIterator can modify the elements in a collection using
set().
d. Traverse: Basic Iterator Iterator can traverse Map, List, and Set.
ListIterator can traverse List objects only.
e. Index: Basic Iterator Iterator has no method to obtain an index of
the element in a collection. Using ListIterator, you can obtain an index of
the element in a collection.
9. How to make class singleton in java?
A. We can create a singleton in java in 3 ways
A. We can create a singleton in java in 3 ways
a. Create singleton as Enum (thread-safe as Enum is by default final in
Java)
public enum Singleton{
INSTANCE;
System.out.println("Singleton using Enum in Java");
}
INSTANCE;
System.out.println("Singleton using Enum in Java");
}
//call
Singleton.INSTANCE;
b. Double-checked locking mechanism (not thread-safe, lazyloading)
public class Singleton{
private volatile Singleton INSTANCE;
private volatile Singleton INSTANCE;
//constructor
private Singleton(){}
public Singleton getInstance(){
if(INSTANCE == null){
synchronized(Singleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
private Singleton(){}
public Singleton getInstance(){
if(INSTANCE == null){
synchronized(Singleton.class){
//double checking Singleton instance
if(INSTANCE == null){
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
c. Static Field initialization (early loading)
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
10. Can we override a static method?
A. Static methods can be overloaded but not overridden.
static methods in Java are resolved at compile time. Since method overriding is part of Runtime Polymorphism, so static methods can't be overridden.
11. Under what circumstances does singleton break?
A. Single breaks in case of reflection, serialization, and cloning.
a. A new instance of the class can be created through reflection without using a constructor and this can break a singleton.
b. When a singleton object is serialized, the deserialized object on another end will not have singleton features.
c. If the parent class of a singleton object implements a cloneable interface then the singleton can be cloned, this will break the singleton nature of the object.
12. What is the use of version id in serialization?
A. Version id keeps track of the changes done to class after it is serialized. Version id is incremented with each change to class. With the help of version id, we can acknowledge that the class has changed since serialization and is no more backward compatible. This information is used while deserializing the class to ensure that the deserialized object is restored to its latest state.
13. Can you append to an uninitialized null string? What is the output of the following code?
A. Yes if the string is a class variable. No, if the String is a local/method variable.
For class variable output is nullxyz
For local variable output is a compiler error. Variable not initialized.
14. What difference between comparable and comparator?
A. comparable is implemented by the comparing class.
Implementing class overrides the compareTo method. It accepts a generic argument of the type of the implementing class.
The comparator has to be implemented outside of comparing class.
it has "compare()" method.
It accepts objects of type Object and returns an int. We can use generics to configure our comparator to accept specific object types.
The comparator can be passed to the "Collections.sort()" method along with the collection to be sorted to get sorted collection based on criteria defined in the comparator.
You can create multiple comparators for a single type.
Comparable can be implemented only once with single criteria as you only implement one interface at a time.
15. What is flatMap in Stream API
A. In addition to mapping each element to its result, a flat map also flattens the result.
eg collection : {{1,2,3},{4,5,6},{7,8,9}}
flattened collection: {1,2,3,4,5,6,7,8,9}
A. Static methods can be overloaded but not overridden.
static methods in Java are resolved at compile time. Since method overriding is part of Runtime Polymorphism, so static methods can't be overridden.
11. Under what circumstances does singleton break?
A. Single breaks in case of reflection, serialization, and cloning.
a. A new instance of the class can be created through reflection without using a constructor and this can break a singleton.
b. When a singleton object is serialized, the deserialized object on another end will not have singleton features.
c. If the parent class of a singleton object implements a cloneable interface then the singleton can be cloned, this will break the singleton nature of the object.
12. What is the use of version id in serialization?
A. Version id keeps track of the changes done to class after it is serialized. Version id is incremented with each change to class. With the help of version id, we can acknowledge that the class has changed since serialization and is no more backward compatible. This information is used while deserializing the class to ensure that the deserialized object is restored to its latest state.
13. Can you append to an uninitialized null string? What is the output of the following code?
A. Yes if the string is a class variable. No, if the String is a local/method variable.
For class variable output is nullxyz
For local variable output is a compiler error. Variable not initialized.
14. What difference between comparable and comparator?
A. comparable is implemented by the comparing class.
Implementing class overrides the compareTo method. It accepts a generic argument of the type of the implementing class.
The comparator has to be implemented outside of comparing class.
it has "compare()" method.
It accepts objects of type Object and returns an int. We can use generics to configure our comparator to accept specific object types.
The comparator can be passed to the "Collections.sort()" method along with the collection to be sorted to get sorted collection based on criteria defined in the comparator.
You can create multiple comparators for a single type.
Comparable can be implemented only once with single criteria as you only implement one interface at a time.
15. What is flatMap in Stream API
A. In addition to mapping each element to its result, a flat map also flattens the result.
eg collection : {{1,2,3},{4,5,6},{7,8,9}}
flattened collection: {1,2,3,4,5,6,7,8,9}
16. Can we skip assess modifier in method/class declaration?
A. Yes. It will get default access.
17. How do annotations work?
A. Annotations in java are implementation of Aspect-oriented programming (AOP).
The aim of AOP is to address applications based on different aspects associated with it. An example of an aspect of an application can be error-handling or Authorization. Aspects are cross-cutting concerns in an application. AOP tries to separate out these concerns from core application logic thereby managing them effectively across the entire application.
Annotations are similar to
interfaces. A consumer is defined for an annotation, which contains code that will get executed when JVM comes across that annotation. Java has a lot of predefined annotations. Consumer for
these annotations is JVM itself.
Java provides some annotations in order to define our custom annotations
@Documented - it is a marker annotation that
tells whether to add an annotation in the Java doc or not.@Retention - It defines how long the
annotation should be kept.RetentionPolicy.SOURCE – Annotation is discarded during the compilation. These
annotations don’t make any sense after the compilation has been completed,
so they aren’t written to the bytecode. Examples:
@Override, @SuppressWarningsRetentionPolicy.CLASS - Annotation is discarded during class load. Useful when doing
bytecode-level post-processing. This is the
default retention policy if nothing is defined.RetentionPolicy.RUNTIME - Annotation is not discarded. The annotation should be
available for reflection at runtime. This is usually used for custom
annotations.@Target - Where annotation can be placed. If
you don’t specify this, annotation can be placed anywhere.@Inherited – Controls whether the annotation
should affect the subclass.Annotations only support primitives, strings, and enumerations. All attributes of annotations are defined as methods, and default values can also be provided.
We can write consumer for annotation using reflection. Reflection API provides Class, method, and Field objects which have a
getAnnotation() method, which returns the
annotation object. We can cast this object as our custom annotation (after
checking with instanceOf()) and then, we can call methods
defined in our custom annotation. 18. What is a functional interface and how does the compiler come to know if it is a functional interface?
A functional interface is an interface that contains only one abstract method.
eg. Runnable, ActionListener, Comparable
Java compiler comes to know if an interface is a functional interface with the help of @FunctionalInterface Annotation.
@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation. This means if your interface has just one abstract method and you have not marked it with @FunctionalInterface, the Java compiler will still treat it as a functional interface.
19. Explain the difference between lambda and anonymous class.
A.In the anonymous classes, the ‘this’ keyword resolves to the anonymous class itself, For lambda expression ‘this’ keyword resolves to enclose class where lambda expression is written.
Another difference between lambda expression and anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and converts them into the private method of the class. It uses invoke dynamic instruction that was added in Java 7 to bind this method dynamically.
Comments
Post a Comment