Show List

Java Interview Questions

 What is the difference between an interface and an abstract class in Java?

In Java, both interfaces and abstract classes are used to define contracts for classes to follow, but they have different characteristics and use cases. Here are the key differences between interfaces and abstract classes:

  1. Methods:

    • Interfaces: In an interface, all methods are implicitly abstract and have no method body. Any class that implements an interface must provide implementations for all the methods declared in the interface.

    • Abstract Classes: In an abstract class, you can have a mix of abstract (unimplemented) and concrete (implemented) methods. Subclasses can choose whether to implement the abstract methods or inherit the concrete methods.

  2. Inheritance:

    • Interfaces: A class can implement multiple interfaces. Java supports multiple interface inheritance, allowing a class to implement multiple interfaces. This is a way to achieve a form of multiple inheritance.

    • Abstract Classes: A class can have only one direct superclass (single inheritance). If you extend an abstract class, you cannot extend another class (abstract or not) simultaneously.

  3. Constructor:

    • Interfaces: Interfaces cannot have constructors. You cannot create instances of an interface.

    • Abstract Classes: Abstract classes can have constructors. Subclasses can call the constructor of the abstract class using the super keyword.

  4. Fields:

    • Interfaces: Fields declared in an interface are implicitly public, static, and final. They are constants and cannot have instance-specific values.

    • Abstract Classes: Abstract classes can have fields with different access modifiers (public, private, protected). These fields can have different values in different subclasses.

  5. Default Methods (introduced in Java 8):

    • Interfaces: Java 8 introduced the concept of default methods in interfaces. A default method provides a default implementation for a method in an interface. Subclasses that do not provide their own implementation will inherit the default method.

    • Abstract Classes: Abstract classes do not support default methods.

  6. Usage:

    • Interfaces: Use interfaces when you want to define a contract for a class that can be implemented by multiple unrelated classes, or when you want to achieve multiple interface inheritance.

    • Abstract Classes: Use abstract classes when you want to provide a common base class with some default behavior and fields that should be shared by subclasses. Abstract classes are helpful when you want to share code among related classes.

In summary, use interfaces when you want to define a contract for classes that may not have a common base class and need to implement multiple contracts. Use abstract classes when you want to provide a common base with shared behavior and fields for related classes. The choice between interfaces and abstract classes depends on the specific design and requirements of your application.

 What is the difference between a HashMap and a Hashtable in Java?

HashMap and Hashtable are both used to store key-value pairs in Java, but they have some important differences:

  1. Synchronization:

    • HashMap: HashMap is not synchronized, meaning it is not thread-safe. If multiple threads access a HashMap concurrently and at least one of the threads modifies the map structurally (e.g., adding or removing elements), it must be synchronized externally.

    • Hashtable: Hashtable is synchronized, making it thread-safe. All of its methods are synchronized, which ensures that it can be safely used by multiple threads without causing concurrent modification exceptions. However, this can come with a performance cost.

  2. Null Keys and Values:

    • HashMap: HashMap allows one null key and multiple null values. This means you can have one key in a HashMap with a null value, and you can have multiple entries with null values.

    • Hashtable: Neither keys nor values in a Hashtable can be null. If you attempt to insert a null key or value, a NullPointerException will be thrown.

  3. Iterating Over Elements:

    • HashMap: The keySet(), values(), and entrySet() methods of a HashMap are not synchronized, which can lead to concurrent modification issues if the map is modified while iterating over its elements.

    • Hashtable: The collection views (e.g., keySet(), values(), and entrySet()) of a Hashtable are synchronized, which means they are safe to iterate over in a multi-threaded environment.

  4. Performance:

    • HashMap: HashMap tends to perform better in most cases, especially in single-threaded applications, due to its lack of synchronization.

    • Hashtable: The synchronization in Hashtable can lead to a performance penalty in multi-threaded scenarios because all method calls are synchronized.

  5. Legacy:

    • Hashtable: Hashtable is considered a legacy class and is generally not recommended for use in modern Java applications. It has been largely replaced by more flexible and efficient data structures, like HashMap.
  6. Concurrency:

    • HashMap: If you need thread safety, you can use ConcurrentHashMap, which provides better concurrency control and performance compared to Hashtable.

In summary, if you need thread safety, you can use Hashtable, but it may come with a performance cost. In most modern applications, HashMap is the preferred choice due to its performance and flexibility. If you need thread safety, you should consider using ConcurrentHashMap or synchronizing a HashMap externally rather than using Hashtable

 What is the difference between a for loop and a for-each loop in Java?

In Java, both regular for loops and enhanced for-each loops (also known as the "enhanced for loop" or "for-each loop") are used for iterating over elements in arrays or collections. However, they have different syntax and use cases:

  1. Regular for Loop:

    • Syntax:


      for (initialization; condition; update) { // Loop body }
    • Use Cases:

      • Regular for loops are used when you need to iterate over a range of values or when you need more control over the loop, such as changing the loop variable inside the loop, skipping iterations, or having complex loop conditions.
    • Example:


      for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
  2. Enhanced for-each Loop:

    • Syntax:


      for (elementType element : collection) { // Loop body }
    • Use Cases:

      • Enhanced for-each loops are used for simple iteration over elements in arrays and collections without the need for an explicit loop variable. They are convenient and readable when you want to process all elements in a collection sequentially.
    • Example (Iterating over an array):


      for (int num : numbers) { System.out.println(num); }
    • Example (Iterating over a collection):

      javaCopy code
      List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); for (String name : names) { System.out.println(name); }

Key Differences:

  • Regular for loops provide more control and flexibility. You can specify initialization, condition, and update expressions, allowing you to perform complex looping operations.

  • Enhanced for-each loops are simpler and more concise, making them a better choice when you need to iterate through all elements of a collection without complex looping logic. They are read-only, meaning you cannot modify the collection or array elements during iteration.

  • Regular for loops are better suited for scenarios where you need to access elements by index or perform non-sequential iteration.

  • Enhanced for-each loops are often used with collections (like lists, sets, or maps) and arrays, where you want to process each element sequentially.

  • The enhanced for-each loop is also known for its enhanced type safety because it eliminates the risk of off-by-one errors and index-related bugs.

A for loop is used to iterate over an array or a collection of items with a specific number of iterations, while a for-each loop is used to iterate over an array or a collection of items without specifying the number of iterations.

 What is the difference between a String and a StringBuilder in Java?

In Java, String and StringBuilder are two classes used for working with text data, but they have different characteristics and are used in different scenarios. Here are the key differences between String and StringBuilder:

  1. Immutability:

    • String: String objects are immutable, which means once a String is created, it cannot be changed. Any operation that appears to modify a String actually creates a new String object. This immutability has implications for memory usage and performance, especially when manipulating strings in a loop.

    • StringBuilder: StringBuilder objects are mutable, allowing you to modify the content of the object without creating new objects. This makes StringBuilder more efficient when you need to perform multiple string modifications.

  2. Performance:

    • String: Because of its immutability, when you concatenate or modify strings in a loop, it can create a large number of temporary objects, which can be inefficient in terms of memory and performance.

    • StringBuilder: StringBuilder is designed for efficient string manipulation. When you need to perform multiple string concatenations or modifications, using a StringBuilder can be significantly faster and more memory-efficient than using String concatenation.

  3. Thread Safety:

    • String: String objects are inherently thread-safe due to their immutability. Multiple threads can safely share and read String objects without the need for synchronization.

    • StringBuilder: StringBuilder is not inherently thread-safe. If you need to use a mutable string builder in a multi-threaded environment, you should synchronize access to it or use StringBuffer, which is a thread-safe version of StringBuilder.

  4. Methods:

    • String: String provides a wide range of methods for string manipulation, searching, and formatting. However, because String is immutable, these methods often return new String objects with the modified content.

    • StringBuilder: StringBuilder provides methods for appending, inserting, deleting, and modifying the content of the string within the same object. This makes it efficient for building and modifying strings.

  5. Use Cases:

    • String: Use String when you have text data that doesn't change frequently and you need the security and immutability that String provides.

    • StringBuilder: Use StringBuilder when you need to perform dynamic or frequent string concatenation, modification, or building operations. It is more suitable for building strings in loops or when efficiency is critical.

 What is the difference between a static and a non-static method in Java?

In Java, methods can be classified as static or non-static (also called instance methods). These two types of methods serve different purposes and have distinct characteristics. Here are the key differences between static and non-static methods:

1. Invocation:

  • Static Method:

    • A static method belongs to the class rather than to any specific instance of the class.
    • It is called on the class itself, using the class name, without the need to create an instance of the class.
  • Non-Static Method (Instance Method):

    • An instance method is associated with an object (instance) of the class.
    • It is called on a specific object of the class and operates on the state of that object.

2. Access to Class Members:

  • Static Method:

    • Static methods can only access other static members (static fields and static methods) of the class.
    • They cannot access instance-specific members directly (instance fields or instance methods) without creating an instance of the class.
  • Non-Static Method:

    • Instance methods can access both static members and instance-specific members of the class. They can use the this keyword to refer to the current instance and its members.

3. Usage:

  • Static Method:

    • Use static methods for utility methods that are not tied to a specific instance's state.
    • Static methods are commonly used for factory methods, helper functions, and methods that perform operations on class-level data.
  • Non-Static Method:

    • Use instance methods for operations that are specific to an instance's state.
    • Non-static methods are used to define the behavior of objects and to interact with their state.

4. Memory Allocation:

  • Static Method:

    • Static methods are loaded into memory when the class is loaded, and they exist in memory as long as the class is loaded.
  • Non-Static Method:

    • Instance methods are created in memory only when an object of the class is instantiated. Each object has its copy of instance methods, and they are released when the object is no longer referenced.

5. Overriding:

  • Static Method:

    • Static methods cannot be overridden because they are associated with the class, not with instances.
  • Non-Static Method:

    • Instance methods can be overridden in subclasses, allowing for polymorphic behavior when the object's type is not known until runtime.

6. Use of "this":

  • Static Method:

    • Static methods cannot use the this keyword because they do not have a reference to a specific instance.
  • Non-Static Method:

    • Instance methods can use the this keyword to refer to the current instance within the method body.

  What is the difference between an Array and an ArrayList in Java?


In Java, arrays and ArrayLists are both used to store collections of elements, but they have different characteristics and use cases. Here are the key differences between arrays and ArrayLists:

  1. Size:

    • Array:

      • Arrays have a fixed size that is determined when they are created. Once the size is set, it cannot be changed. If you need to change the size, you have to create a new array and copy the elements from the old array.
    • ArrayList:

      • ArrayLists are dynamic in size. They can grow or shrink as needed. You can add or remove elements at runtime without worrying about the size.
  2. Type:

    • Array:

      • Arrays can hold elements of a specific data type. Once the type is defined, it cannot be changed.
    • ArrayList:

      • ArrayLists can hold elements of any data type because they are generic classes. You can use them to store objects of different types.
  3. Mutability:

    • Array:

      • Arrays are mutable, meaning you can change the value of an element at a specific index. However, you cannot change the size of the array.
    • ArrayList:

      • ArrayLists are mutable as well, allowing you to add, remove, or modify elements in the list, and they can grow or shrink as needed.
  4. Performance:

    • Array:

      • Arrays are generally faster and more memory-efficient than ArrayLists because they have a fixed size, and the JVM can optimize them better.
    • ArrayList:

      • ArrayLists have some overhead due to their dynamic sizing. They may consume more memory and have a slight performance cost compared to arrays.
  5. Initialization:

    • Array:

      • You need to specify the size of an array at the time of creation. For example, int[] myArray = new int[5]; creates an integer array with a fixed size of 5.
    • ArrayList:

      • You can create an ArrayList without specifying the size. For example, ArrayList<Integer> myList = new ArrayList<>(); creates an ArrayList of integers with an initial capacity that can grow as needed.
  6. Primitives vs. Objects:

    • Array:

      • Arrays can store both primitive data types (e.g., int, char) and objects, but they treat primitive data types differently.
    • ArrayList:

      • ArrayLists can only store objects (reference types). To store primitive data types, you must use their corresponding wrapper classes (e.g., Integer, Character).
  7. Length/Size:

    • Array:

      • Arrays use the length property to get their size.
    • ArrayList:

      • ArrayLists use the size() method to get their size.

7.      What is the difference between a throw and a throws in Java?

A "throw" is used to explicitly throw an exception, while "throws" is used in the method signature to indicate that a method can throw an exception.

8.      What is the difference between a final variable and a constant variable in Java?

A final variable can be assigned a value only once and its value cannot be modified thereafter, while a constant variable must be assigned a value at the time of declaration and its value cannot be modified.

9.      What is a constructor in Java?

A constructor is a special method that is used to initialize an object when it is created. A constructor has the same name as the class and does not have a return type.

10.   What is the purpose of the main method in Java?

The main method is the entry point of a Java program. It is the method that is executed when the program starts. The main method must be declared as public, static, and have a specific signature, "public static void main(String[] args)".

11.   What is the difference between == and equals() in Java?

The == operator compares the memory address of two objects, while the equals() method compares the content of two objects.

12.   What is a JVM in Java?

A JVM (Java Virtual Machine) is an abstract computing machine that enables a computer to run Java programs. It interprets compiled Java code and converts it into machine-readable instructions.

13.   What is a JRE in Java?

A JRE (Java Runtime Environment) is a software package that contains a JVM, the Java class libraries, and other resources that are necessary to run Java programs.

14.   What is a JDK in Java?

A JDK (Java Development Kit) is a software development environment that contains a JRE, the Java compiler, and other tools that are necessary to develop, debug, and run Java programs.

15.   What is the difference between a primitive data type and a non-primitive data type in Java?

A primitive data type is a basic data type that is built into the Java language, such as int, char, and boolean. A non-primitive data type is a data type that is derived from the primitive data types, such as String, Array, and classes.

16.   What is the purpose of the super keyword in Java?

The super keyword is used to refer to the superclass of an object. It can be used to call the methods or constructors of the superclass, or to access the variables of the superclass.

17.   What is the purpose of the final keyword in Java?

The final keyword can be used to declare a variable, method, or class as final. A final variable cannot be modified after it is assigned a value. A final method cannot be overridden, and a final class cannot be extended.

18.   What is an exception in Java?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are used to handle errors and other exceptional conditions that might occur during the execution of a program.

19.   What is an exception handler in Java?

An exception handler is code that stipulates what a program will do when an anomalous event disrupts the normal flow of that program's instructions. An exception, in a computer context, is an unplanned event that occurs while a program is executing and disrupts the flow of its instructions

20.   What is a Map in Java?

A Map is an interface that represents a collection of key-value pairs. It allows you to store and retrieve elements based on a unique key, rather than an index.

21.   What is a Thread in Java?

A Thread is a lightweight unit of execution that can run concurrently with other threads. It allows you to perform multiple tasks simultaneously, improving the performance and responsiveness of your Java application.

22.   What is the difference between a Thread and a Runnable in Java?

A Thread is a class that extends the Object class and implements the Runnable interface. A Runnable is an interface that allows you to define a task that can be executed by a Thread.

23.   What is a Lambda Expression in Java?

A Lambda Expression is a short, anonymous function that can be passed as an argument to a method or used to define a functional interface. They were introduced in Java 8, and they simplify the code and improve the readability of functional programming constructs.

24.   What is a Stream in Java?

A Stream is a sequence of elements that can be processed in parallel or sequentially. They were introduced in Java 8, and they provide a functional approach to working with collections of data.

25.   What is a File in Java?

A File is a class that represents a file or directory on a file system. It provides methods for creating, reading, writing, and deleting files, as well as for querying file attributes and performing other file-related operations.

26.   What is the difference between a File and a Path in Java?

A Path represents a file or directory as an abstract concept, while a File represents a file or directory on a file system. A Path can be used to manipulate and access the file system, while a File is used to perform specific file operations such as reading and writing.

27.   What is the difference between a Path and a File in Java?

A Path represents a file or directory as an abstract concept, while a File represents a file or directory on a file system. A Path can be used to manipulate and access the file system, while a File is used to perform specific file operations such as reading and writing.

28.   What is a Servlet in Java?

A Servlet is a Java class that runs on a server and processes HTTP requests and generates HTTP responses. They are commonly used to create dynamic web applications.

29.   What is a JSP in Java?

A JSP (JavaServer Page) is a Java-based technology that allows you to create dynamic web pages by embedding Java code within HTML. JSPs are translated into Servlets at runtime.

30.   What is a JDBC in Java?

JDBC (Java Database Connectivity) is a Java API that allows you to connect to and interact with a relational database. It provides a set of classes and interfaces for querying and updating a database.

31.   What is a JPA in Java?

JPA (Java Persistence API) is a Java specification for accessing and manipulating relational data. It provides an object-relational mapping (ORM) to interact with the database and a set of annotations for mapping Java classes to database tables.

32.   What is a JUnit in Java?

JUnit is a Java framework for writing and running automated unit tests. It provides annotations and assertions for testing the behavior of individual units of code.

33.   What is a Maven in Java?

Maven is a Java-based build tool that automates the process of building and managing Java projects. It provides a standard structure for the project and manages dependencies and plugins.

34.   What is a Spring in Java?

Spring is a Java framework for building Java applications. It provides a set of modules for different areas of development, such as data access, web development, and security.

35.   What is a Hibernate in Java?

Hibernate is a Java-based ORM (Object-Relational Mapping) framework that allows you to map relational data to Java objects and vice versa. It provides a set of APIs for querying and updating the database, and it can be used with the Spring framework.

36.   What is a REST in Java?

REST (Representational State Transfer) is an architectural style for building web services. RESTful web services are based on the HTTP protocol and use standard HTTP methods such as GET, POST, PUT, and DELETE to perform operations on resources.

37.What is the issue in below code:

String inputStr = "abcd";
char[] input = inputStr.toCharArray(); String newStr = input[0]+input[1]+input[2];

The code provided attempts to create a new String from individual characters in the char array input. However, there is an issue in the way you're concatenating the characters. In Java, when you use the + operator to concatenate characters, it doesn't result in a String. Instead, it performs numeric addition because characters are treated as numeric values (their Unicode code points).

To create a String from characters, you should use the String.valueOf(char) method or construct a String using a character array. Here's how you can fix the code:

Using String.valueOf(char):

char[] input = inputStr.toCharArray(); String newStr = String.valueOf(input[0]) + input[1] + input[2];

Using a character array:

char[] input = inputStr.toCharArray(); String newStr = new String(new char[] { input[0], input[1], input[2] });

Either of these approaches will correctly create a String newStr that contains the characters at the specified positions in the input array.


    Leave a Comment


  • captcha text