Skip to main content

Top Core Java Interview Questions


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.
Due to the above rules laid down in Java 8, the diamond problem does not occur during multiple inheritances.

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
        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.
 
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 :
List<String> list = new ArrayList<>();
list.foreach(System.out::println);

Using special for loop: 
for(dataType item : array) {
    ...
}
Using traditional for loop:
for(int i=0; i< arr.length-1; i++) {
    ...
}

8. Difference Between iterator and list iterator?
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. 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");
    }

//call
Singleton.INSTANCE;

b. Double-checked locking mechanism (not thread-safe, lazyloading)

public class Singleton{
     
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;
     
}
}

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;
    }
}

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}

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@SuppressWarnings
RetentionPolicy.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

Popular posts from this blog

Intercommunication in the world of micro services

I always wondered what can be the different ways in which the microservices can commmunicate with each other. Like majority of us I almost instintively thought of REST or SOAP as two prominant ways of passing data over internet, but are there other better ways of making the different components of an enterprise systen talk to each other? If yes what is the purpose of their existance, lets address these and other related queries in this article. The manner in which micro services talk to each other can be classified in four major categories: Synchronous Communication Asynchronous Communication Database Level Communication Hybrid Lets explore them one by one -  Synchronous Communication In this style of inter service communication a sender service requests some resource from its counterpart and then waits for the response before proceeding ahead. This is also called blocking mode because the caller is blocked till it gets wahat it had requested. Lets explore some protocols which use ...

Spark Checkpointing,Union, Lineage And Partioning

I have been working on apache spark lately and wanted to consolidated my learnings at one place so that I can refer later and make it available to other developers as well. While working with spark you will often run into situations where the way you write code normally results in most inefficient results. You can visualise spark plan executions but it is very tedious to navigate and make sense of in terms of what exactly is cause of the problem. In such case having basic knowledge of how spark manages tasks can help arrive at solutions to improve compute efficiency. Below are a set of techniques I have used to improve compute efficiency of spark applications. SparkContext with a Checkpoint Directory In  Apache Spark , the  SparkContext  is the entry point to interact with the Spark framework. It manages the execution of jobs, resource allocation, and coordination across clusters. A  checkpoint directory  in Spark is used to store  checkpointed RDDs or stre...

Java 21: 1 Hour Crash Course

Let’s embark on a  journey to discover the most important parts of Java 21 . I’ll cover the essentials, highlight new features in Java 21, and provide code samples and explanations. At the end of this article you’ll get a solid foundation and pointers for deeper study. Let's get started! Java 21: 1 Hour Crash Course 1. Introduction Java  is a powerful, object-oriented programming language. Java 21, released in September 2023, brings performance improvements and new features. Prerequisites: Basic programming concepts (variables, loops, functions). Java installed (JDK 21). 2. Your First Program public class HelloWorld { public static void main ( String [ ] args ) { System . out . println ( "Hello, Java 21!" ) ; } } public class HelloWorld  — Defines a class. public static void main  — Entry point. System.out.println  — Prints to console. 3. Variables and Data Types int age = 25 ; double price = 19.99 ; boolean isJavaFun = true ...