Saturday, September 9, 2023

Top 20 Essential Java Interview Questions with Answers for Freshers with 1 to 2 years Experienced

If you are a grad looking for an internship position in a company that uses Java, or a fresher, just out from college and looking out for a Java development position, then this post is for you. I have attended, taken, and participated in different levels of Java interviews. I can say there is a vast difference between them, which is not surprising because you obviously want to ask different level questions based upon whether the candidate is fresher or experienced. Similarly, the problem at phone interviews, written tests, and face-to-face interviews, keeping this in mind, and give you always have a limited amount of time before going for an interview, It's essential to prepare the right set of questions.

Well, I can't guarantee that you will see questions from this set on your interview, but it gives you an idea about the level of questions you can expect in any Java internship or Software trainee position.

Don't bother about multithreading and complex topic, only basic knowledge of threads is enough. Similarly, put more emphasis on the data structure, algorithms, and object-oriented basics like Inheritance, Composition, Encapsulation, Polymorphism, etc.

Similarly, Java interviews are not just about Java questions, it is also expected from you that you know computer fundamentals, basics of Linux and SQL, basics of designing software, coding, networking fundamentals, etc.

Once you have good ideas on those topics, you are ready for your interview. Though, if you are confused about how to prepare well for all those topics, I can suggest two ways, read a book like Cracking the Coding Interview book by Gayle Laakmann McDowell, which contains 189 questions and their answers on all these topics.

basic questions for Java programmers



The second way is to join a course like Master The Coding Interview Bootcamp: Algorithms + Data Structures on Udemy. Though it is not as comprehensive as the Cracking the Coding Interview book, it does explain the most crucial thing algorithms and data structure.


You can also supplement your preparation through courses by joining a couple of others to prepare SQL, Java, Linux, etc. I have shared my full list of courses for coding interviews here, which contains some of the best routes to prepare well for programming job interviews.


Java Interview Questions for 1 to 2 years Experienced Programmers

Anyway, let's start with some of the basics Java questions a programmer with 1 to 2 years of experience should know.




1) What's, is Polymorphism in Java or OOP? (answer)
Polymorphism in Java and OOP allows objects of different classes to be treated as objects of a common superclass. Compile-time polymorphism is resolved during compilation and involves method overloading. 

It occurs when multiple methods in the same class share the same name but have different parameters. Run-time polymorphism is resolved during execution and involves method overriding. It occurs when a subclass provides a specific implementation of a method already defined in its superclass. 

The appropriate method is determined at runtime based on the actual type of the object, promoting code flexibility and reusability.


2) Given a reference to an abstract class Shape that has an abstract method named Draw, how does Java determine which version of the draw to call? What portion is handled at runtime, and what portion at compile time?  (answer)

In Java, when you have a reference to an abstract class like "Shape" with an abstract method "draw," the determination of which version of "draw" to call is handled at runtime. This is known as runtime polymorphism or dynamic method dispatch. 

At compile time, the Java compiler ensures that the method "draw" is declared in the abstract class "Shape," but it doesn't know which specific subclass will be instantiated at runtime.

The decision about which subclass's implementation of "draw" to invoke is resolved dynamically based on the actual object's type that the reference points to when the method is called. 

Java's virtual method table (VMT) or v-table is used to make this determination at runtime, allowing for flexibility and extensibility in object-oriented programming.


3) what is the difference between an array and a linked list? How does this affect performance and memory usage? (answer)
Arrays and linked lists are data structures, but they differ in key aspects. Arrays provide fast random access to elements, as elements are stored in contiguous memory locations. In contrast, linked lists use nodes with references to the next element, offering dynamic sizing and efficient insertions and deletions but slower random access.

Performance: Arrays excel in random access, making them ideal for search and retrieval operations. Linked lists are efficient for insertions and deletions, especially at the beginning or middle of the list.

Memory: Arrays have fixed sizes, potentially wasting memory, while linked lists use memory more efficiently as nodes can be allocated as needed.

Choose based on the specific use case: arrays for fast access and predictable size, linked lists for dynamic resizing and frequent insertions/deletions.


4) Describe the garbage collection. What do mark and sweep mean? How about generational garbage collection? (answer)
Garbage collection is a memory management process in programming languages, like Java, to automatically reclaim memory occupied by objects no longer in use.

"Mark and Sweep" is a classic garbage collection algorithm. It involves two phases: marking and sweeping. During marking, the system identifies reachable objects, typically starting from the root objects, marking connected objects as "in use." 

The sweeping phase then reclaims memory occupied by unmarked, unreachable objects, making it available for new allocations.

Generational garbage collection divides memory into generations (usually young and old). New objects are allocated in the young generation. As objects survive collections, they are promoted to the older generation. 

This approach optimizes efficiency by recognizing that most objects become unreachable shortly after creation, allowing the young generation to be collected more frequently.


5) what is the difference between a string literal and a string object? (answer)
A string literal is a sequence of characters enclosed in double quotes, like "Hello, World!". It represents a fixed, immutable string value. String literals are stored in a special memory area called the string pool, and when you create a string literal, Java checks if it already exists in the pool and reuses it if found. This helps conserve memory.

A string object, on the other hand, is an instance of the String class. It represents a mutable sequence of characters and allows various operations like concatenation or substring extraction. String objects are stored in the heap memory, and when you create one using the new keyword, a new memory location is allocated. String literals and objects serve different purposes, with literals offering optimization benefits.


6) what is the difference between int and Integer? (answer)
In Java, int and Integer are related but have key distinctions.

Primitive vs. Wrapper: int is a primitive data type, while Integer is a wrapper class for primitive int. int is more memory-efficient and faster for basic arithmetic operations, while Integer is an object with added functionality.

Nullability: int cannot be null, while Integer can. This allows Integer to represent the absence of a value, which is helpful in certain scenarios.

Autoboxing/Unboxing: Java provides automatic conversion between int and Integer through autoboxing (converting int to Integer) and unboxing (converting Integer to int) mechanisms.

Generally, prefer int for simple arithmetic and memory efficiency. Use Integer when you need an object that can represent null or for compatibility with Java's collection classes that work with objects, not primitives.


7) what is a binary search tree?  How do you implement it in Java? (answer)
A binary search tree (BST) is a hierarchical data structure in which each node has at most two children, typically referred to as the left and right child. It satisfies the binary search property: for each node, all elements in its left subtree are less than the node's value, and all elements in its right subtree are greater. This property enables efficient searching, insertion, and deletion operations, making BSTs valuable in computer science and various applications.

To implement a BST in Java, you create a class representing a node with left and right references and implement methods for insertion, deletion, and searching. Recursion is often used to traverse and manipulate the tree. 

Here's a simplified example:


You would then build the tree by inserting nodes and perform various operations according to the binary search property.


8) what is a heap memory in Java? (answer)
Heap memory in Java refers to the portion of a computer's memory where objects are allocated and deallocated during the program's runtime. Unlike the stack, which stores method call frames and local variables, the heap is dynamic and used for objects that may have varying lifetimes.

Heap memory management in Java is automatic, thanks to the garbage collector. When objects are no longer referenced or reachable by the program, the garbage collector identifies them and reclaims their memory, preventing memory leaks.

Java developers do not need to explicitly allocate or deallocate memory in the heap; the JVM (Java Virtual Machine) handles this automatically, ensuring efficient memory usage and preventing memory-related errors like memory leaks and buffer overflows.

9) how would you implement a priority queue in Java without using built-in PriorityQueue class? (answer)
You can implement a priority queue in Java without using the built-in PriorityQueue class by creating your custom data structure based on a binary heap. 

Here's a simplified implementation:

import java.util.Arrays;

public class CustomPriorityQueue {
    private int[] heap;
    private int size;
    private static final int DEFAULT_CAPACITY = 10;

    public CustomPriorityQueue() {
        heap = new int[DEFAULT_CAPACITY];
        size = 0;
    }

    public void add(int value) {
        if (size == heap.length) {
            heap = Arrays.copyOf(heap, 2 * heap.length);
        }

        heap[size] = value;
        size++;
        heapifyUp(size - 1);
    }

    public int poll() {
        if (isEmpty()) {
            throw new IllegalStateException("Priority queue is empty.");
        }

        int root = heap[0];
        heap[0] = heap[size - 1];
        size--;
        heapifyDown(0);
        return root;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    private void heapifyUp(int index) {
        int parent = (index - 1) / 2;
        while (index > 0 && heap[index] < heap[parent]) {
            swap(index, parent);
            index = parent;
            parent = (index - 1) / 2;
        }
    }

    private void heapifyDown(int index) {
        int leftChild = 2 * index + 1;
        int rightChild = 2 * index + 2;
        int smallest = index;

        if (leftChild < size && heap[leftChild] < heap[smallest]) {
            smallest = leftChild;
        }

        if (rightChild < size && heap[rightChild] < heap[smallest]) {
            smallest = rightChild;
        }

        if (smallest != index) {
            swap(index, smallest);
            heapifyDown(smallest);
        }
    }

    private void swap(int i, int j) {
        int temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }
}
This implementation provides a basic priority queue using a binary min-heap. You can add elements with add(), remove the highest-priority element with poll(), and check if it's empty with isEmpty(). Adjust the implementation as needed for your specific requirements.


10) what does "Big O of n" mean in practice? Will an O(n) algorithm always outperform an O(n*n) algorithm? (answer)
"Big O of n" (O(n)) denotes linear time complexity in algorithm analysis. It means that as the input size (n) increases, the algorithm's execution time grows linearly. In practice, O(n) algorithms are generally efficient and perform well for moderate-sized inputs. However, an O(n) algorithm may not always outperform an O(n^2) (quadratic) algorithm for all input sizes. 

The choice between them depends on factors like the actual data, constant factors, and hardware. For larger inputs, the O(n^2) algorithm may become slower. Therefore, while O(n) is usually more efficient, it's essential to analyze your specific use case and consider performance trade-offs.

Here is a quick chart explaining Big-O complexity and what they mean in simple word:
what does "Big O of n" mean in practice? Will an O(n) algorithm always outperform an O(n*n) algorithm?



11) What is the difference between a list and a linked list in Java? (answer)
In Java, a "list" is a fundamental interface that represents an ordered collection of elements, allowing for the presence of duplicate elements. Lists can be implemented using various classes, and they offer various trade-offs between performance and functionality.

On the other hand, a "linked list" is a specific implementation of a list in Java, provided by the java.util.LinkedList class. Unlike some other list implementations, a linked list stores its elements as nodes, each containing a reference to the next node in the sequence. 

This structure makes linked lists particularly efficient for frequent insertions and deletions in the middle of the list. However, they are less efficient than other list types, such as arrays, when it comes to random access to elements.


12) What is a map in Java? (answer)
In Java, a map is a data structure that stores key-value pairs, allowing you to associate each key with a corresponding value. It's part of the Java Collections Framework and is implemented by the java.util.Map interface. 

Maps provide efficient retrieval and storage of data based on keys and are used for various purposes, such as storing configuration settings, caching, and managing data relationships.

Common implementations of maps in Java include HashMap, TreeMap, and LinkedHashMap. Each implementation has unique characteristics, making them suitable for different use cases, from fast retrieval with HashMap to ordered keys with TreeMap.


13) What is an array in Java? (answer)
In Java, an array is a data structure that allows you to store a fixed-size, ordered collection of elements of the same data type. Arrays provide a way to store multiple values under a single variable name, making it easier to work with collections of data.

Key characteristics of arrays in Java include:
  • Fixed Size: Once the size of an array is defined, it cannot be changed during runtime.
  • Homogeneous Elements: All elements in an array must be of the same data type.
  • Zero-Based Indexing: Array elements are accessed using indices starting from 0.
Arrays are widely used in Java for tasks such as storing and manipulating data, iterating through collections, and performing various algorithms and calculations.


14) What is a thread in Java? (answer)
In Java, a thread is the smallest unit of execution within a program. Threads are lightweight sub-processes that run concurrently and share the same memory space, allowing multiple tasks to be executed simultaneously. They are used to achieve multitasking and parallelism in Java applications.

Java supports multithreading through the java.lang.Thread class, which can be extended or used directly to create and manage threads. Threads enable developers to perform tasks concurrently, improving performance and responsiveness in applications, particularly in scenarios like performing background operations, handling user interface interactions, or optimizing CPU utilization. Java provides built-in mechanisms for thread synchronization and communication to ensure data consistency and coordination among threads.

15) What is a lock in Java? (answer)
In Java, a lock is a synchronization mechanism used to control access to shared resources in a multi-threaded environment. It ensures that only one thread can access a particular resource or section of code at a time, preventing data corruption and race conditions.

Java provides various types of locks, with the most common being the synchronized keyword, which allows you to create synchronized blocks or methods to protect critical sections of code. Additionally, Java offers more advanced locks like ReentrantLock and ReadWriteLock, which provide greater flexibility and control over thread synchronization.

Locks are crucial for managing thread safety and ensuring proper synchronization when multiple threads are concurrently accessing shared data or resources.

16) What is deadlock in Java? (answer)
Deadlock is a situation in concurrent computing where two or more threads or processes become stuck in a state of waiting for each other to release resources, preventing any of them from making progress. It typically occurs when multiple threads or processes compete for limited resources, like locks or shared memory, in a way that leads to a circular dependency. 

As a result, none of the involved threads or processes can proceed, causing the entire system to become unresponsive. Detecting and resolving deadlocks is essential in concurrent programming to ensure system reliability and prevent resource contention issues that can lead to performance degradation or system failure.


17) Difference between Overloading and Overriding? (answer)
In object-oriented programming, overloading and overriding are distinct concepts. Overloading occurs within a single class when you have multiple methods with the same name but different parameters. It enables you to provide multiple versions of a method within the same class to handle various input scenarios, and it's resolved at compile-time based on the method's signature. 

On the other hand, overriding comes into play in inheritance when a subclass provides its own implementation for a method that is already defined in its superclass. This enables the subclass to customize or extend the behavior of the inherited method, and it's resolved at runtime based on the actual object's type.

18) Difference between abstract class and interface? (answer)
In Java, abstract classes and interfaces are tools for defining abstract methods and establishing contracts for implementing classes. However, they differ in several ways. An abstract class can contain both abstract and concrete methods, allowing for a mix of unimplemented and implemented functionality. 

It can also have fields, including static and non-static ones, and constructors for initialization. However, abstract classes support single inheritance, meaning a class can extend only one abstract class. 

On the other hand, interfaces can only have abstract methods (prior to Java 8), but they allow fields that are implicitly public, static, and final. Interfaces do not support constructors and offer the advantage of multiple inheritance, as a class can implement multiple interfaces. 

The choice between abstract classes and interfaces depends on your specific design and flexibility needs.

19) Difference between Process and Thread in Java? (answer)
In Java, processes and threads are both units of execution, but they serve different purposes and have distinct characteristics. A process represents an independent program with its own memory space and resources, making it heavyweight and well-suited for running multiple applications in isolation. Communication between processes typically involves more complex mechanisms like inter-process communication (IPC). 

On the other hand, threads are lightweight units that share memory space and resources within a single process. They are used for concurrent execution within a single application, enabling tasks to run concurrently and share data more easily.

In Java, threads are managed by the JVM and are part of the same Java application, making them suitable for tasks that require parallelism and efficient resource sharing.

20) Difference between "extends" thread and "implements" Runnable? (answer)
In Java, the difference between extending the Thread class and implementing the Runnable interface pertains to the approach for creating threads. When you extend the Thread class, you essentially create a new class that is a thread itself. 

This class inherits thread-related methods like start() and run(). However, this approach has limitations because Java supports single inheritance, meaning your subclass cannot extend any other class simultaneously. 

On the other hand, implementing the Runnable interface allows you to define the thread's behavior within a separate class, leaving your main class free to extend other classes if needed. It's a more flexible and recommended approach for creating threads in Java.

And, finally

Top 20 Java Interview Questions with Answers for Programmers with 1 to 2 years Experience


That's all in this list of interview questions for preparing Java internship and Software developer positions. These questions are just to give you an idea of the level, which is expected from fresher’s and trainees. Keeping yourself on to a higher level will surely benefit you. Don't forget to share what kind of questions was asked of you in a fresher level interview.


Other Interview Questions Articles you may like to explore
  • Top 10 Spring Framework Interview Questions with Answers (see here)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • 10 frequently asked Servlet Interview Questions with Answers (see here)
  • 21 String programming interview questions (string questions)
  • 20 jQuery Interview Questions for Java Web Developers (list)
  • 10 Hibernate Interview Questions for Java EE developers (see here)
  • Top 10 EJB Interview Questions and Answers (see here)
  • Top 10 JMS and MQ Series Interview Questions and Answers (list)
  • Review these 50 Java questions before interviews (review)
  • 10 Great JDBC Interview Questions for Java Programmers (questions)
  • 15 Java NIO and Networking Interview Questions with Answers (see here)
  • Top 10 XSLT Interview Questions with Answers (read more)
  • 15 Data Structure and Algorithm Questions from Java Interviews (read here)
  • Top 10 Trick Java Interview Questions and Answers (see here)
  • Top 40 Core Java Phone Interview Questions with Answers (list)
  • 20+ Array Interview Questions for Programmers (array questions)
  • 21 String programming interview questions (string questions)
  • 25 system design interview questions (system design)
  • 20+ Binary tree interview questions for interviews (binary tree questions)
  • 10 XML Interview Questions for Java Programmers (read here)
  • 20 Java Design Pattern Questions asked on Interviews (see here)
  • 10 Struts Interview Questions for Java developers (list)
  • 20 Tibco Rendezvous and EMS Interview Questions (read more)
  • 10 Oracle Interview Questions for Java developers (see here)
  • Top 10 JSP Questions  from J2EE Interviews (read here)
  • 12 RESTful Web Services Questions from Interviews (read here)
  • 100+ coding problems and some tips to crack programming interview (questions)

Thanks for reading this article so far. If you find these essential Java Interview questions useful then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note. 

P. S. - If you are looking for a free online course to prepare for Java interviews then you can also check out these Java Interview Prep Courses. It contains the best online courses to prepare for Java developer interviews, both for freshers and experienced programmers with 2 to 10 years of experienced. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.