Java Interview Questions and Answers

Top 50 Java Interview Questions and Answers

Find the most asked Java Interview Questions along with their answers on this page. These Java Interview Questions are for freshers and experienced professionals and are commonly asked in technical interviews.

What is JAVA


Java is a versatile, platform-independent programming language known for its object-oriented nature, security features, and robustness. It allows developers to write code once and run it on different platforms, making it widely used in various applications, including web development, Android app development, and server-side programming.

Where JAVA is used?

  1. Web Development: Java for dynamic websites and Spring/JSF frameworks.
  2. Android App Development: Primary language for Android apps.
  3. Enterprise Applications: Large-scale, secure server apps with Java EE.
  4. Desktop Applications: Cross-platform GUIs using Swing/JavaFX.
  5. Big Data and Analytics: In Apache Hadoop, Spark, data tools.
  6. Embedded Systems: IoT and secure embedded systems.
  7. Scientific Research: Versatile tool for research projects.
  8. Gaming: 2D/3D games with LibGDX, jMonkeyEngine.

JAVA Interview Questions and Answers For Freshers

Ques 1: What are the main features of JAVA?


  1. Platform Independence: Java’s “write once, run anywhere” feature is achieved by compiling applications into bytecode, which can run on any platform with a Java Virtual Machine (JVM), ensuring high portability.
  2. Object-Oriented: Java is built on OOP principles, focusing on classes, objects, encapsulation, inheritance, and polymorphism. OOP enhances modularity and code reusability in Java applications.
  3. Automatic Memory Management (Garbage Collection):Java has an automatic garbage collector that cleans up unused memory, preventing memory issues and making memory management easier for developers.
  4. Strongly Typed and Statically Typed: Java is both strongly typed (variables require explicit type declarations) and statically typed (type checking happens at compile-time, reducing runtime type errors).
  5. Multi-Threading Support: Java simplifies concurrent and parallel programming with built-in support for multi-threading. It offers robust thread management tools through the java.lang.Thread class and the java.util.concurrent package.
  6. Rich Standard Library:
    Java includes a rich standard library, known as the Java Standard Library or Java API, offering a vast array of pre-built classes and packages for tasks like data manipulation, networking, I/O operations, and more.
  7. Exception Handling: Java provides strong exception handling mechanisms, enabling developers to gracefully manage errors. This separation of error-handling from regular code enhances the reliability of Java applications.
  8. Security: Java prioritizes security, incorporating features like bytecode verification, a security manager, and a standardized cryptography API. This focus on security makes Java a popular choice for building secure applications, especially in web and enterprise settings.


Ques 2: What is a class?


Class is a blueprint or template from which objects are created and describes the contents of the object. A class should be defined before creating an object.

Ques 3: What is the difference between JDK, JRE and JVM?


AspectJDK (Java Development Kit)JRE (Java Runtime Environment)JVM (Java Virtual Machine)
Purpose Used for Java development, including writing, compiling, and debugging code.Used for executing Java applications. It contains the necessary runtime environment.Executes Java bytecode on a specific platform.
Components– Compiler (javac) for source code to bytecode conversion. – Debugger (jdb) for debugging. – Various tools and utilities.– Java libraries and core classes. – JVM (Java Virtual Machine) for running Java bytecode.– Responsible for executing Java bytecode. – Different implementations for various platforms.
Necessity for Running Java CodeNot required on the end-user’s machine to run Java applications.Required on the end-user’s machine to run Java applications.Required on the end-user’s machine to execute Java applications.
Platform IndependenceCode can be developed on one platform and executed on another with the appropriate JRE.Provides the runtime environment needed to run Java applications on a specific platform.Executes Java bytecode on the user’s machine, making it platform-dependent.
Use in DevelopmentEssential for writing and compiling Java code.Not used during development but needed for running Java applications.Not used directly in development, as it’s responsible for executing compiled Java bytecode.

Ques 4: Explain Virtual Machine (JVM) architecture.


Class Loader Subsystem:

  • Responsible for loading classes and interfaces.
  • Utilizes class loaders (Bootstrap, Extension, Application) to load classes from various sources.
  • Class Area stores class-level information, including bytecode and static data.

Runtime Data Areas:

  • Heap: Allocates memory for objects and their data during runtime. Divided into Young Generation (new objects), Old Generation (long-lived objects), and in older JVMs, the Permanent Generation (metadata).
  • Java Stack: Each thread has its own stack, used for method invocation and storing local variables.

Execution Engine:

  • Just-In-Time (JIT) Compiler: Converts bytecode to native machine code for performance optimization.
  • Interpreter: Initially interprets bytecode and switches to JIT-compiled code for frequently executed methods.

Native Interface:

  • Enables interaction between Java code and native (e.g., C/C++) code.
  • Serves as a bridge between platform-independent Java and platform-specific native libraries.

Native Method Libraries:

  • Contains native methods specific to the underlying platform.
  • Provides access to low-level resources and system functions.

Direct Memory Access (DMA):

  • Allows the JVM to access native memory directly, useful for certain performance-critical tasks.

Thread Management and Synchronization:

  • Manages threads, ensuring safe and efficient execution in multi-threaded applications.
  • Includes a Thread Scheduler and synchronization mechanisms.

Garbage Collector:

  • Reclaims memory occupied by objects no longer in use.
  • Employs various garbage collection algorithms for memory optimization.

Execution Monitoring and Profiling:

  • Monitors and profiles application performance, collecting data on memory usage, CPU utilization, and more.

Security Manager:

  • Enforces security policies to restrict potentially harmful operations by Java applications, enhancing overall security.

The JVM architecture abstracts hardware intricacies, providing a platform-independent environment for running Java applications. Its components work together to execute Java bytecode efficiently, manage memory, and ensure security and reliability.

Ques 5: What are the data types in JAVA?


Java, like many programming languages, has several built-in data types that you can use to store and manipulate different kinds of data. These data types can be categorized into two main categories: primitive data types and reference data types.


Primitive Data Types:

  • byte: 8-bit signed integer. Range: -128 to 127.
  • short: 16-bit signed integer. Range: -32,768 to 32,767.
  • int: 32-bit signed integer. Range: -2^31 to (2^31 – 1).
  • long: 64-bit signed integer. Range: -2^63 to (2^63 – 1).
  • float: 32-bit floating-point number. Used for decimal values. Example: 3.14f.
  • double: 64-bit floating-point number. Used for decimal values with higher precision. Example: 3.14.
  • char: 16-bit Unicode character. Represents a single character, such as ‘A’ or ‘5’.
  • boolean: Represents true or false values.

Reference Data Types:

  • Classes: User-defined types created using class definitions.
  • Interfaces: User-defined types that define a set of abstract methods.
  • Arrays: Ordered collections of elements of the same data type. Arrays can hold both primitive and reference types.
  • Enumerations (Enums): A special data type used to define a set of constants.
  • Strings: A sequence of characters. Although it behaves like a reference type, it is implemented as an object in Java.


Ques 6: Explain the difference between primitive and reference types in JAVA.


Primitive Types: Hold simple data values directly, are memory-efficient, and have default values. Examples include int, boolean, and char.

Reference Types: Store references to objects, are used for complex data structures, have default value null, and can have associated methods. Examples include classes, interfaces, and arrays.

Ques 7: What is the lambda expression in JAVA?


A lambda expression in Java is a compact way to define and use anonymous functions. It simplifies code, especially when working with functional interfaces. Here’s a brief example:

BinaryOperator add = (a, b) -> a + b; int result = add.apply(5, 3); // result will be 8

In this example, `(a, b) -> a + b` is a lambda expression representing a function that adds two numbers. It’s assigned to a `BinaryOperator` functional interface, and you can use it with the `apply` method to add two integers.

Ques 8: Is Java cross-platform, and if it is, what makes it possible?


Java is cross-platform due to its use of the Java Virtual Machine (JVM). Code is compiled to bytecode, which runs on any system with a compatible JVM. Platform-independent libraries, portability, a strong community, and adherence to standards further enhance cross-platform compatibility.

Ques 9: What is the difference between Java and C++


Syntax and Language FeaturesSimpler and more consistent syntaxMore complex syntax with features like operator overloading and pointers
Memory ManagementAutomatic memory management (garbage collection)Manual memory management using new and delete
Platform IndependencePlatform-independent through JVMPlatform-dependent, requires recompilation for different platforms
CompilationCompiled to bytecode, executed by JVMCompiled directly to machine code for the target platform
Standard LibrariesComprehensive Java Standard LibraryRich C++ Standard Library including STL for data structures and algorithms

Ques 10: What is JVM?



The Java Virtual Machine (JVM) is a critical part of the Java programming platform. It executes Java programs by interpreting or compiling bytecode, manages memory, ensures platform independence, and provides security features. It’s key to Java’s “Write Once, Run Anywhere” capability.

Ques 11: What are the consequences if we do not declare the `main` method as `static` in Java?


If we do not declare the main method as static in Java, we will get a compilation error, and our program will not run. The static keyword is necessary because it allows the JVM to invoke the main method without creating an instance of the class, main is a fundamental requirement in Java to serve as the entry point for your program, and not adhering to this convention will result in compilation errors and prevent your program from running.

Ques 12: Define Copy constructor in java.

Ans. In Java, a copy constructor is a special type of constructor that allows us to create a new object by copying the values of an existing object of the same class. It is a constructor that takes an object of the same class as a parameter and initializes the new object with the values of the existing object. Here’s a typical structure for a copy constructor in Java:
public class MyClass {
    private int value;

    // Copy constructor
    public MyClass(MyClass other) {
        this.value = other.value;

    // Other constructors and methods for MyClass
In the above example, the `MyClass` class has a copy constructor that takes another `MyClass` object (`other`) as a parameter and copies its `value` field to initialize the new object. This allows you to create a new object with the same state as an existing object, making it convenient for object cloning or duplication.

Ques 13: What are shallow copy and deep copy in java?



Shallow Copy: Copies the object and its references, so both the original and the copy share the same referenced objects. Changes to those shared objects affect both copies.

Deep Copy: Creates a new object and duplicates all referenced objects recursively. It results in two completely independent copies with no shared references. Changes to one copy don’t affect the other.

Ques 14: How do you declare variable in JAVA?


In Java, you can declare variables by specifying their data type, followed by the variable name. Here’s the basic syntax for declaring variables:

data_type variable_name;

Ques 15: What is Autoboxing and Unboxing in JAVA?



Autoboxing: Converting a primitive type to its corresponding wrapper class object.
Example: `Char` to `Character`.

Unboxing: Converting a wrapper class object to its corresponding primitive type.
Example: `Character` to `Char`.

Both Autoboxing and unboxing allow you to work with primitives as objects and vice versa in Java.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Java Related Interview Questions

Ques 16: What is the purpose of the "finally" block in exception handeling?


The `finally` block in exception handling ensures that specific code is always executed, whether an exception is thrown or not. It’s commonly used for cleanup operations and guarantees execution even in exceptional situations.

Ques 17: How does JAVA garbage collection work?


Explanation of how Java garbage collection works:

  1. Memory Allocation: Objects are created in memory (heap) during program execution.
  2. Reference Counting: Java keeps track of references to objects. When an object is no longer referenced, it becomes eligible for garbage collection.
  3. GC Roots: The process starts from GC roots (e.g., local variables, static variables) and traces reachable objects.
  4. Mark and Sweep: Unreachable objects are marked and then swept (removed) from memory.
  5. Generational GC: Objects are categorized into young and old generations, allowing for efficient collection.
  6. Tuning: Developers can tune GC settings to optimize memory management for specific applications.

Ques 18: What is method overriding in JAVA?


 If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods. Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

Ques 19: What is method overloading in JAVA?


Method overloading in Java is a feature that allows you to define multiple methods in a class with the same name but different parameter lists (different types or numbers of parameters). The key distinction among overloaded methods is the method signature, which includes the method name and the parameter types. Here are the main characteristics of method overloading:

  • Same Method Name: In method overloading, all the overloaded methods have the same name.
  • Different Parameter Lists: Overloaded methods have different parameter lists, which means they can differ in the number of parameters, the types of parameters, or both.
  • Return Type: The return type of an overloaded method can be the same or different. However, Java considers only the method signature, not the return type, when determining which overloaded method to invoke.
  • Access Modifiers: Overloaded methods can have different access modifiers (public, private, protected, or package-private) but must be defined within the same class.
  • Exception: Overloaded methods can declare different checked exceptions in their throws clause, but they must not declare different unchecked exceptions (subclasses of RuntimeException) because that would change the method signature. 

Ques 20: What do you mean by data encapsulation?


Data encapsulation in OOP means bundling data (attributes) and methods (functions) into a single unit (a class) and controlling access to that data. It hides the internal details, provides security, and promotes code organization and flexibility.

JAVA Interview Questions and Answers For Experienced.

Ques 21: Differentiate between Volatile and Transient Variable in Java.


AspectVolatile VariableTransient Variable
Purpose Ensures visibility of a variable’s value across threads.Marks a variable so it’s not serialized when an object is converted to bytes (e.g., for storage or transmission).
Type of VariableCan be applied to instance variables (object fields).Can be applied to instance variables (object fields).
Thread VisibilityGuarantees visibility and ordering of reads and writes among threads.Not related to thread visibility or synchronization.
Synchronization Provides a memory barrier, ensuring that reads and writes are seen consistently by all threads.Not related to synchronization or thread safety.
Serialization Not related to serialization.Prevents a variable from being serialized when the object is serialized.
UsageCommonly used for variables that are shared among threads, such as flags or status indicators.Used when you want to exclude specific fields from being serialized, often because they are not serializable or should not be persisted.

Ques 22: What is the "java.util.concurrent.ThreadPoolExecutor" class in Java?


The ThreadPoolExecutor class in Java is a tool for managing a pool of worker threads to efficiently execute tasks concurrently. It provides control over thread creation, task submission, and thread termination, making it easier to build efficient multithreaded applications.

Ques 23: What is the "java.util.LinkedHashMap" class in Java?


The `java.util.LinkedHashMap` class in Java is a map that combines hash table functionality with a linked list to maintain the order of elements based on their insertion order. It’s useful when you need to preserve the order of elements in a map.

Ques 24: What is a Memory Leak? Discuss some common causes of it.



A memory leak occurs when a program doesn’t release memory it no longer needs, leading to increased memory usage. Common causes include not freeing allocated memory, retaining references to unnecessary objects, and not releasing non-memory resources like files or sockets.

Main causes of memory leak:

  • Not Releasing Allocated Memory: Failing to explicitly free or deallocate memory that has been allocated for objects or data.
  • Unused References: Holding references to objects that are no longer needed, preventing the memory from being reclaimed.
  • Cyclic References: Objects referencing each other in a cycle, preventing the garbage collector from reclaiming their memory.
  • Resource Leaks: Not releasing non-memory resources like file handles, database connections, or network sockets.
  • Static Variables: Keeping references to objects in static variables can extend their lifetime unnecessarily.
  • Memory Pools: Failing to release memory from custom memory pools or caches.

Ques 25: What are the different categories of Java Design patterns?


Java design patterns are categorized into three main categories:

  1. Creational Patterns: These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. Common examples include Singleton, Factory, and Builder patterns.
  2. Structural Patterns: Structural patterns focus on how objects are composed to form larger structures. Examples include Adapter, Bridge, and Composite patterns.
  3. Behavioral Patterns: These patterns are concerned with the interaction and responsibility of objects. Examples include Observer, Strategy, and Command patterns.

These design patterns provide solutions to recurring design problems and promote code reusability, maintainability, and flexibility in Java applications.


JAVA Interview Questions and Answers

Ques 26: Can you explain the Java thread lifecycle?


The Java thread lifecycle describes the various states a thread can go through during its execution in a Java program. Threads in Java follow a well-defined lifecycle, which consists of several states. Here is an explanation of the Java thread lifecycle:

New: The thread is created but not yet started.

Runnable: Ready to run, waiting for CPU time.

Running: Actively executing its code.

Blocked/Waiting: Awaiting a certain condition.

Timed Waiting: Waiting with a timeout.

Terminated: Execution has completed or been terminated.

Ques 27: How does an exception propagate in the code?


An exception propagates in the code by moving up the call stack. When an exception is thrown in a method and not caught locally, it searches up the method call hierarchy until it finds an appropriate exception handler (a catch block). If it doesn’t find one, the program terminates, and the exception is reported.

Ques 28: What is "completeableFuture" class in JAVA?


The CompletableFuture class in Java is part of the java.util.concurrent package and represents a Future that can also be completed with a value or exception by application code. It is a powerful construct for asynchronous programming, allowing you to work with asynchronous tasks and their results in a more flexible and composable way.

Some main features of completeableFuture class

  • Asynchronous Operations: `CompletableFuture` handles asynchronous tasks and result handling.
  • Combining Operations: You can link multiple tasks together with methods like `thenCombine`.
  • Exception Handling: It offers mechanisms to manage exceptions in asynchronous tasks.
  • Timeouts and Delays: You can control execution timing with timeouts and delays.
  • Completion Callbacks: Attach callbacks to handle task completion using methods like `thenAccept`.
  • Combining Multiple Results: Combine results from multiple tasks with methods like `allOf`.
  • Exception Handling (Again: It provides further exception handling options for robust error management.

Ques 29: In Java, aside from security implications, what technical justifications exist for enforcing immutability on strings?


Enforcing immutability on strings in Java has several technical justifications beyond security implications. Immutability provides numerous benefits in terms of performance, reliability, and simplicity in multi-threaded environments. Here are some technical justifications for enforcing immutability on strings:

  • Thread Safety: Immutable strings are naturally safe in multi-threaded environments, simplifying concurrency.
  • Performance: They allow caching and reuse, improving performance.
  • Predictable Hash Codes: Stable hash codes are essential for data structures like HashMap.
  • Functional Programming: Immutability aligns with functional programming.
  • Safe Sharing: Immutable strings can be shared without worry of unintended changes.
  • API Design: It leads to robust APIs by preventing unexpected modifications.
  • Optimizations: Compilers can optimize immutable objects, enhancing efficiency.
  • Memory Management: Immutability reduces memory issues and leaks.
  • Consistency: It maintains a consistent program state.
  • API Stability: Immutable classes remain stable across Java versions.


Ques 30: How would you differentiate between a String, StringBuffer, and a StringBuilder?

Aspect String StringBuffer StringBuilder
Mutability Immutable: Cannot be changed Mutable: Can be changed safely Mutable: Can be changed safely
Performance Not efficient for frequent modifications due to creating new objects More efficient than String for frequent modifications More efficient than both String and StringBuffer for frequent modifications
Thread Safety Thread-safe (immutable), no synchronization needed Thread-safe (synchronized), safe for multiple threads Not thread-safe (unsynchronized), not safe for multiple thread
Usage When the content won’t change frequently When the content may change frequently in a multi-threaded environment When the content may change frequently in a single-threaded environment
Operations Limited mutability operations like concatenation with “+”, substring, etc. Extensive mutability operations like append, insert, delete, replace, etc. Extensive mutability operations like append, insert, delete, replace, etc.

Java Questions Asked in Interview

Ques 31: What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?


In Java, threads can be assigned different priorities to influence their scheduling by the JVM’s thread scheduler. Thread priorities are represented as integer values, and they range from 1 (the lowest priority) to 10 (the highest priority). The constant values Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, and Thread.MAX_PRIORITY are provided to represent the minimum, default, and maximum priority levels, respectively. Here are the different types of thread priorities:

Certainly, here’s a concise summary:

  • Minimum Priority(Thread.MIN_PRIORITY or 1) : Lowest priority, gets CPU time when higher-priority threads are not runnable.
  • Default Priority (Thread.NORM_PRIORITY or 5):  Default for new threads, mid-range priority.
  • Maximum Priority (Thread.MAX_PRIORITY or 10): Highest priority, gets more CPU time. 

Thread priorities can vary by OS. Default is usually 5. Use `setPriority()` to change within the range 1-10.

Ques 32: What is the difference between the program and the process?


DefinitionA set of instructions or code written in a programming language.An executing instance of a program.
StateStatic and passive, stored on disk or in memory, waiting to be executed.Dynamic and active, running in memory with its own resources.
Execution Does not consume system resources until it is executed.
Consumes system resources (CPU, memory, etc.) while running.
IndependenceDoes not run independently; it’s a blueprint for a task.Can run independently and concurrently with other processes.
Interaction Cannot interact with other programs or processes.Can interact with other processes, including inter-process communication.
Management Not managed by the operating system.Managed by the operating system, which schedules and allocates resources.

Ques 33: What do you mean by Collections in Java? What are the constituents of Collections in Java?


In Java, “Collections” refers to a framework and a set of classes and interfaces that provide a unified way to work with groups of objects. Collections allow you to store, manipulate, and access groups of elements in a structured and efficient manner. Key constituents of Collections in Java include:

  • Interfaces: Such as `List`, `Set`, and `Map`, which define common behaviors for collections.
  • Classes: Such as `ArrayList`, `HashSet`, and `HashMap`, which implement these interfaces and provide concrete data structures for collections.
  • Algorithms: A set of utility methods to perform common operations on collections, such as sorting, searching, and manipulating elements.

Collections in Java make it easier to work with data in various forms, from simple lists and sets to more complex mappings. They provide a foundation for efficient and flexible data handling in Java applications.

Ques 34: Can we change the scope of the overridden method in the subclass?


No, in Java, you cannot change the scope (i.e., access modifier) of an overridden method in a subclass. When you override a method in a subclass, you must match the access modifier of the overridden method in the superclass. This principle is known as the “rule of method overriding” and ensures that the subclass maintains the same or broader visibility for the overridden method but cannot reduce its visibility.

Here are the rules:

  1. If a superclass method is declared as `public`, the overriding method in the subclass must also be `public`.
  2.  If a superclass method is declared as `protected`, the overriding method in the subclass can be `protected` or `public`, but not `private` or package-private.
  3. If a superclass method is declared as package-private (no access modifier), the overriding method in the subclass must also be package-private (or `protected` or `public` within the same package).
  4. If a superclass method is declared as `private`, it cannot be overridden in a subclass because it is not accessible from the subclass.

In summary, when you override a method in a subclass, you can maintain or broaden the visibility of the method but cannot reduce it. Changing the access modifier to something more restrictive (e.g., from `public` to `private`) would result in a compilation error.

Ques 35: What is the difference between static (class) method and instance method?


AspectStatic (class)instance method
Accessing attributesCannot access instance attributes (unless passed as a parameter)Can access instance attributes directly
Accessing class-level attributesCan access class-level attributes directlyCannot access class-level attributes directly
UsageTypically used for utility functions or operations that don’t depend on instance-specific dataUsed for operations that depend on and manipulate instance-specific data
Accessing with objectCan be called on the class itself or on an instance of the classCan only be called on an instance of the class
SyntaxDefined using the @staticmethod decorator or by using the class nameDefined without any specific decorator
ExampleMyClass.static_method() or obj.static_method()obj.instance_method()

Ques 36: What are the differences between abstract class and interface?


AspectAbstract ClassInterface
DefinitionAn abstract class can have a mixture of abstract (unimplemented) and concrete (implemented) methods.An interface contains only abstract (unimplemented) methods and constants (static final fields).
InheritanceA class can extend only one abstract class.A class can implement multiple interfaces.
ConstructorsAn abstract class can have constructors, and they are called when a subclass is instantiated.An interface cannot have constructors because it cannot be instantiated on its own.
Method ImplementationIn an abstract class, you can provide method implementations (concrete methods).In an interface, all methods are abstract and have no implementation in the interface itself.
Access ModifiersYou can use different access modifiers (public, protected, private) for abstract class members.All interface members are implicitly public and cannot have access modifiers other than public.
PurposeAbstract classes are typically used when you want to provide a common base with some shared functionality among related classes.Interfaces are used to define a contract that multiple unrelated classes can implement, enabling polymorphism.

Ques 37: What is string pooling?



The string pool in Java is a memory optimization technique where string literals are stored and reused. When you create a string with a value that already exists in the pool, Java reuses the existing object, reducing memory usage. This is done automatically for string literals, and you can also use `String.intern()` to add strings to the pool explicitly. Strings in the pool are not immediately eligible for garbage collection, so use this feature judiciously to manage memory effectively.

Ques 38: Explain JPA in Java.


JPA stands for Java Persistence API. It is a Java specification for managing relational data in Java applications. JPA provides a standard way to interact with relational databases, allowing developers to work with database records as Java objects. It is part of the Java EE (Enterprise Edition) and Java SE (Standard Edition) platforms.

Here are some key aspects and concepts of JPA:

  • ORM: It maps Java objects to database tables.
  • Entity Classes: These represent database objects, annotated to define mappings.
  • EntityManager: Manages entity lifecycle and database operations.
  • JPQL: A Java-based query language for database queries.
  • Persistence Unit: Configures entities and database connections.
  • Annotations: Define mappings with annotations like @Entity and @Table.
  • Relationships: Support for defining relationships between entities.
  • Caching: Provides caching for improved performance.
  • Transaction Management: Integrates with Java EE or Spring for transaction handling.
  • Vendor-Specific Implementations: Various vendor-specific implementations are available (e.g., Hibernate, EclipseLink).

Ques 39: Explain the different authentications in Java Servlets.


Java Servlets can implement various authentication mechanisms to secure web applications. The primary authentication methods in Java Servlets include:

  • HTTP Basic and Digest Authentication: Basic prompts for credentials, while Digest sends hashed passwords.
  • Form-Based Authentication: Custom login forms for username/password input.
  • Container-Managed (Java EE) Security: Configuration-based security in web.xml.
  • Custom Authentication: Implement custom logic with filters or servlets.
  • Single Sign-On (SSO): Enable users to log in once for multiple apps.
  • Token-Based Authentication: Use tokens like JWT for authentication.
  • LDAP Authentication: Authenticate against directory services.
  • Database Authentication: Validate user credentials against a database.

Ques 40: Explain the difference between parallelism and concurrency in the context of Java.


DefinitionMultiple tasks are managed to overlap or interleave their execution, but not necessarily simultaneously.Multiple tasks are executed simultaneously, often on separate CPU cores or processors.
Implication for PerformanceMay improve program responsiveness by efficiently using CPU time when some tasks are blocked (e.g., I/O operations).Improves performance by processing tasks simultaneously, typically for CPU-bound workloads.
CPU UsageTypically uses a single CPU core and switches between tasks, achieving concurrency through time-sharing.Utilizes multiple CPU cores or processors, allowing tasks to run truly concurrently.
Typical Use CasesI/O-bound operations, where tasks may block and wait for external resources (e.g., reading/writing files, network requests).CPU-bound tasks, such as data processing, scientific simulations, and rendering.
Java ExamplesJava’s Executor framework, java.util.concurrent package, and synchronized keyword facilitate concurrency.Java’s ForkJoinPool, the Stream API’s parallel() method, and Parallel Streams enable parallelism.

JAVA Interview Questions and Answers for Coding

Ques 41: Write code Check if the given string is Palindrome or not

import java.util.Scanner;

public class StringIsAPalindromeOrNot {

	public static void main(String[] args) {
		Scanner sc =new Scanner(;
		 System.out.println("Enter string");
		String s =;
		String rev = "";
		for (int i = s.length()-1; i >=0 ; i--) 
			System.out.println("String is palindrome");
			System.out.println("String is not palindrome");



Ques 42: Write code to Calculate frequency of characters in a string

import java.util.Scanner;

public class FrequencyOfCharactersInAString {
   public static void main(String[] args) {
    Scanner sc =new Scanner(;
     System.out.print("Enter String : ");
     String str = sc.nextLine(); 
     int[] freq = new int[str.length()]; 
     int i, j; 

     //Converts given string into character array 
     char string[] = str.toCharArray(); 
     for(i = 0; i <str.length(); i++) { 
        freq[i] = 1; 
          for(j = i+1; j <str.length(); j++) { 
            if(string[i] == string[j]) { 

           //Set string[j] to 0 to avoid printing visited character 
            string[j] = '0'; 
    //Displays the each character and their corresponding frequency 
    System.out.println("Characters and their corresponding frequencies"); 
    for(i = 0; i <freq.length; i++) { 
       if(string[i] != ' ' && string[i] != '0') 
          System.out.println(string[i] + "-" + freq[i]); 

Ques 43: How is the merge sort algorithm implemented?

//Java Program for Merge Sort
class Main {
  // this function display the array
  public static void display(int[] arr, int size) {
    for (int i = 0; i < size; i++) {
      System.out.print(arr[i] + " ");
  // main function of the program
  public static void main(String[] args) {
    int[] a = {

    int size = a.length;
    display(a, size);

    mergeSort(a, 0, size - 1);
    display(a, size);

  // this function apply merging and sorting in the array
  static void mergeSort(int[] a, int left, int right) {
    int mid;
    if (left < right) {
      // can also use mid = left + (right - left) / 2
      // this can avoid data type overflow
      mid = (left + right) / 2;

      // recursive calls to sort first half and second half sub-arrays
      mergeSort(a, left, mid);
      mergeSort(a, mid + 1, right);
      merge(a, left, mid, right);
  // after sorting this function merge the array
  static void merge(int[] arr, int left, int mid, int right) {
    int i, j, k;
    int n1 = mid - left + 1;
    int n2 = right - mid;

    // create temp arrays to store left and right sub-arrays
    int L[] = new int[n1];
    int R[] = new int[n2];

    // Copying data to temp arrays L[] and R[]
    for (i = 0; i < n1; i++)
      L[i] = arr[left + i];
    for (j = 0; j < n2; j++)
      R[j] = arr[mid + 1 + j];

    // here we merge the temp arrays back into arr[l..r]
    i = 0; // Starting index of L[i]
    j = 0; // Starting index of R[i]
    k = left; // Starting index of merged sub-array

    while (i < n1 && j < n2) {
      // place the smaller item at arr[k] pos
      if (L[i] <= R[j]) {
        arr[k] = L[i];
      } else {
        arr[k] = R[j];
    // Copy the remaining elements of L[], if any
    while (i < n1) {
      arr[k] = L[i];
    // Copy the remaining elements of R[], if any
    while (j < n2) {
      arr[k] = R[j];

Ques 44: Find non-repeating characters in a string

import java.util.*;

class Solution 
    public static void main (String[]args) 
        Scanner sc = new Scanner (;
        System.out.println ("Enter the string");

        String str = ();	//Taking input as a string from the user
        int freq[] = new int[256];

        //Calculating frequency of each character
        for (int i = 0; i < str.length (); i++)
            freq[str.charAt (i)]++;

        System.out.println ("The non repeating characters are : ");

        for (int i = 0; i < 256; i++)
            if (freq[i] == 1)	//finding the character whose frequency is 1
	            System.out.print ((char) i + " ");

Ques 45: Write a code to replace a substring in a string.

//Replace Substring in a String Java code
import java.util.Scanner;
public class ReplaceASubstringInAString {
public static void main(String[] args) {
     Scanner sc = new Scanner(;
     System.out.print("Enter a String : ");
     String s1 = sc.nextLine();
     System.out.print("Enter the String to be replaced : ");
     String oldString = sc.nextLine();
     System.out.print("Enter the new String : ");
     String newString =sc.nextLine();

     String replaceString = s1.replace(oldString, newString);
     System.out.println("New String is :"+replaceString);

JAVA Interview Questions and Answers For DSA

Ques 46: Write a code for Heap sort.

// Java program for implementation of Heap Sort 
public class PrepInsta
    //Main() for the execution of the program 
    public static void main(String args[]) 
          int a[] = {12, 11, 13, 5, 6, 7}; 
          int len = a.length;

           PrepInsta ob = new PrepInsta(); 

            System.out.println("Sorted array is"); 
           public void sort(int a[]) 
                  int len = a.length; 

                 // Build heap (rearrange array) 
                 for (int i = len / 2 - 1; i >= 0; i--) 
                 heapify(a, len, i); 

                 // One by one extract an element from heap 
                 for (int i=len-1; i>=0; i--) 
                         // Move current root to end 
                          int temp = a[0]; 
                          a[0] = a[i]; 
                          a[i] = temp; 

                           // call max heapify on the reduced heap 
                           heapify(a, i, 0); 

         // To heapify a subtree rooted with node i which is 
        // an index in arr[]. n is size of heap 
       void heapify(int a[], int len, int i) 
              int largest = i; // Initialize largest as root 
              int l = 2*i + 1; // left = 2*i + 1 
              int r = 2*i + 2; // right = 2*i + 2 

               // If left child is larger than root 
               if (l < len && a[l] > a[largest]) 
               largest = l; 

               // If right child is larger than largest so far 
               if (r < len && a[r] > a[largest]) 
               largest = r; 

               // If largest is not root 
               if (largest != i) 
                        int swap = a[i]; 
                        a[i] = a[largest]; 
                        a[largest] = swap; 

                       // Recursively heapify the affected sub-tree 
                         heapify(a, len, largest); 

           /* A utility function to print array of size n */
           static void printArray(int a[]) 
                     int len = a.length; 
                     for (int i=0; i<len; ++i) 
                     System.out.print(a[i]+" "); 


Ques 47: Write a code to replace each element in an array by its rank in the array

import java.util.*;
class Main {
    static void changeArr(int[] input)
        // Copy input array into newArray
        int newArray[] = Arrays.copyOfRange(input, 0, input.length);
        // Sort newArray[] in ascending order
        for(int i=0; i< input.length; i++){
        for(int j=0; j< input.length; j++){
                input[i] = j+1;
    // Driver Code
    public static void main(String[] args)
        // Given array arr[]
        int[] arr = { 100, 2, 70, 12 , 90};
        // Function Call
        // Print the array elements

Ques48: Write a code to find circular rotation of an array by K positions.

class Main {
    /*Function to left rotate arr[] of size n by d*/
    static void leftRotate(int arr[], int d, int n) {
        for (int i = 0; i < d; i++) leftRotatebyOne(arr, n);
    static void leftRotatebyOne(int arr[], int n) {
        int i, temp;
        temp = arr[0];
        for (= 0; i < n - 1; i++) arr[i] = arr[+ 1];
        arr[- 1] = temp;
    /* utility function to print an array */
    static void printArray(int arr[], int n) {
        for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");
    // Driver program to test above functions
    static void main(String[] args) {
        // RotateArray rotate = new RotateArray();
        int arr[] = {1, 2, 3, 4, 5};
        leftRotate(arr, 2, 5);
        printArray(arr, 5);

Ques 49: Write a code to find non-repeating elements in an array.

import java.util.Arrays;

class Main
   public static void countFreq(int arr[], int n)
         boolean visited[] = new boolean[n];
         Arrays.fill(visited, false);
         // Traverse through array elements and
         // count frequencies
         for (int i = 0; i < n; i++) {

            // Skip this element if already processed
            if (visited[i] == true)

            // Count frequency
            int count = 1;
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                   visited[j] = true;
} // Driver code public static void main(String []args) { int arr[] = new int[]{10, 30, 40, 20, 10, 20, 50, 10}; int n = arr.length; countFreq(arr, n); } }

Ques 50: Write a code to find non-repeating elements in an array.

import java.util.Arrays;

class Main
   public static void countFreq(int arr[], int n)
         boolean visited[] = new boolean[n];
         Arrays.fill(visited, false);
         // Traverse through array elements and
         // count frequencies
         for (int i = 0; i < n; i++) {

            // Skip this element if already processed
            if (visited[i] == true)

            // Count frequency
            int count = 1;
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                   visited[j] = true;
} // Driver code public static void main(String []args) { int arr[] = new int[]{10, 30, 40, 20, 10, 20, 50, 10}; int n = arr.length; countFreq(arr, n); } }

Getting Ready for Interviews


In conclusion, this JAVA Interview Questions and Answers page serves as a valuable resource for both aspiring and experienced Java developers. It covers a wide range of topics, providing insightful responses to common interview questions. Whether you’re preparing for a job interview or simply looking to enhance your Java knowledge, the information here will undoubtedly be of great assistance in your journey. Good luck with your JAVA interviews!

Additionally, always remember that JAVA Interview Questions and Answers are your key to success in Java interviews. Revisiting and mastering the content provided here can greatly improve your confidence and performance during these interviews. Best of luck in your Java career endeavors!

Join Our Interview Course Now to Get Yourself Prepared -

Join Our Interview Course Now to Get Yourself Prepared

Prepare for the interview process in both Service and Product Based companies along with Group Discussion, Puzzles, Resume Building, HR, MR and Technical Interviews.