100 Java interview Questions and Answers PDF 2025

Java Interview Questions PDF

Java plays a big role in the current tech industry. It is a versatile programming language widely used for building applications, from web services to mobile apps. Java’s object-oriented nature allows developers to create modular programs, making it easier to manage and scale projects.

Professionals working with Java should be familiar with data structures, algorithms, and core concepts of the language such as class, inheritance, and polymorphism. Java professionals are expected to know object-oriented programming (OOP), Java frameworks like Spring or Hibernate, databases, APIs, multithreading, exception handling, and sometimes real-time problem-solving using Java code.

Preparing for a Java interview is very important because it’s not just about understanding theory, you also need to show practical skills, explain concepts clearly, and solve coding challenges or real-life problems using Java. Good preparation helps you feel confident, answer technical questions smoothly, and stand out from other candidates.

Here, we are sharing many popular Java interview questions and answers, from fresher to experienced candidates. We will provide a PDF download so you can also prepare offline.

Top Java interview Questions and Answers for Freshers

First, we will share popular basic java interview questions and answers, focusing on fresh candidates preparing for java roles.

1. What are the main features of Java?

Answer:

  • Object-Oriented
  • Platform Independent
  • Secure
  • Robust
  • Multithreaded
  • High Performance (via JVM and JIT compiler)

2. What is the difference between JDK, JRE, and JVM?

Answer:

ComponentDescription
JDKJava Development Kit – includes tools and compiler
JREJava Runtime Environment – provides libraries and JVM
JVMJava Virtual Machine – runs Java bytecode

3. What are primitive data types in Java?

Answer:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

4. What is the difference between == and .Equals() in Java?

Answer:

  • == checks reference (memory address) equality
  • .equals() checks logical value equality (can be overridden in classes)

Example:

String a = new String("Test");
String b = new String("Test");
System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true

5. What is method overloading?

Answer:
Method overloading means defining multiple methods with the same name but different parameters in the same class.

Example:

void print(int a) {}
void print(String a) {}

6. What is method overriding?

Answer:
Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.

class Animal {
  void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
  void sound() { System.out.println("Bark"); }
}

7. What is the purpose of the Final keyword?

Answer:

  • final variable: cannot be changed
  • final method: cannot be overridden
  • final class: cannot be extended

8. What is inheritance in Java?

Answer:
Inheritance allows one class to inherit properties and methods from another class using the extends keyword.

class Parent {}
class Child extends Parent {}

9. What is polymorphism?

Answer:
Polymorphism allows methods to perform different behaviors based on the object. It includes method overloading and overriding.

10. What is an interface in Java?

Answer:
An interface is a contract that contains method signatures without implementations.

interface Animal {
  void sound();
}

A class can implement an interface using the implements keyword.

11. What is the difference between abstract class and interface?

Answer:

Abstract ClassInterface
Can have method bodyOnly method signatures (Java 7)
Can have constructorsCannot have constructors
Supports multiple inheritance via interfacesSupports multiple inheritance

12. What is a constructor?

Answer:
A constructor is a special method used to initialize objects. It has the same name as the class and no return type.

class Car {
  Car() { System.out.println("Car created"); }
}

13. What are the performance implications of using ArrayList vs LinkedList?

Answer:

  • ArrayList: Faster for indexed access (O(1)), slower for inserts/removals (O(n)).
  • LinkedList: Slower access (O(n)), but better for frequent insertions/deletions.
    Choose based on access patterns.

14. How does Java’s exception propagation work?

Answer:
If an exception is not caught in a method, it propagates up the call stack. Java lets you handle it using try-catch blocks or declare it with throws.

15. What is the difference between “checked” and “unchecked” exceptions?

Answer:

  • Checked exceptions: must be handled using try-catch or declared with throws (e.g., IOException)
  • Unchecked exceptions: runtime errors (e.g., NullPointerException)

16. What are access modifiers in Java?

Answer:

  • private: accessible within the class
  • default (no modifier): accessible within the package
  • protected: accessible within package and subclass
  • public: accessible everywhere

17. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

ClassThread-SafeMutableUse Case
StringNoNoConstant values
StringBuilderNoYesFaster in single-threaded
StringBufferYesYesThread-safe needs

18. What is garbage collection in Java?

Answer:
Garbage collection is the automatic process of removing unused objects from memory to free up resources. It is managed by the JVM.

19. What is multithreading in Java?

Answer:
Multithreading allows concurrent execution of two or more threads to maximize CPU usage.

class MyThread extends Thread {
  public void run() {
    System.out.println("Thread running");
  }
}

20. What is the use of the “This” keyword in Java?

Answer:

  • Refers to the current class instance
  • Used to avoid confusion between class variables and parameters
  • Can be used to call other constructors in the same class
class Car {
  String color;
  Car(String color) {
    this.color = color;
  }
}

Also Check: Java Interview Questions for Freshers

Que 21. What is JDK, JRE, and JVM?

Answer:

  • JDK (Java Development Kit): A full-featured software development kit used to develop Java applications. It includes JRE and development tools like javac, javadoc, etc.
  • JRE (Java Runtime Environment): A package that provides libraries, JVM, and other components to run Java applications.
  • JVM (Java Virtual Machine): An abstract machine that executes Java bytecode. It is platform-dependent and provides portability.

Que 22. What is the significance of the transient keyword in Java?

Answer: The transient keyword is used to prevent a variable from being serialized. During the serialization process, the value of transient variables is not saved.

class User implements Serializable {
    String name;
    transient String password; // will not be serialized
}

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

Answer:

  • == checks for reference equality, i.e., whether two references point to the same object in memory.
  • .equals() checks for value/content equality, and is often overridden in classes like String.

Example:

String a = new String("Hello");
String b = new String("Hello");
System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true

Que 24. What are constructors in Java?

Answer:
A constructor is a special method used to initialize objects. It has the same name as the class and does not have a return type.

Types:

  • Default Constructor: No parameters.
  • Parameterized Constructor: Accepts parameters to initialize fields.

Example:

public class Car {
  String model;
  Car(String m) {
    model = m;
  }
}

Que 25. What is the difference between ArrayList and LinkedList?

Answer:

FeatureArrayListLinkedList
Data StructureDynamic arrayDoubly linked list
Access TimeFast random accessSlower (sequential access)
Insertion/DeletionSlower (shifting elements)Faster at beginning or middle
Memory UsageLess memoryMore due to node pointers

Choose based on access vs. insertion/deletion performance needs.

Que 26. Explain the concept of Type Erasure in Java Generics and its implications.

Answer:
Type erasure is a process by which the Java compiler replaces all generic type parameters with their bounds or Object type during compilation. This means that generic type information is not available at runtime.

How it works:

  • List<String> becomes List<Object> or List<E> (where E is the type parameter).
  • The compiler inserts casts to ensure type safety at compile time.

Implications:

  • No runtime type information: You cannot use instanceof with generic types (e.g., obj instanceof List<String> is a compile-time error).
  • Cannot create instances of type parameters: new T() is not allowed.
  • Cannot create arrays of type parameters: new T[10] is not allowed.
  • Overloading methods with generic types: You cannot overload methods if their erased signatures are the same (e.g., void print(List<String> list) and void print(List<Integer> list) would clash).
  • Backward compatibility: Type erasure ensures backward compatibility with older Java versions that did not support generics.

While type erasure can sometimes be confusing, it allows generics to be implemented without significant changes to the JVM, maintaining performance and compatibility.

Que 27. How has the role of interfaces evolved in Java 8 and beyond?

Answer:
Java 8 introduced default and static methods in interfaces, allowing some implementation. This narrowed the gap between abstract classes and interfaces, enabling more flexible API design.

Que 28. What is method overloading and overriding?

Answer:

  • Overloading: Same method name with different parameters within the same class. It’s compile-time polymorphism.
  • Overriding: Subclass provides specific implementation for a method defined in the parent class. It’s runtime polymorphism.

Example:

class Example {
  void show(int a) {}
  void show(String b) {} // Overloaded

  class Sub extends Example {
    @Override
    void show(int a) {} // Overridden
  }
}

Que 29. What is the use of the FINAL keyword?

Answer:

  • final variable: Cannot be reassigned.
  • final method: Cannot be overridden.
  • final class: Cannot be subclassed.

It provides stability, consistency, and control in Java programs.

Que 30. How does garbage collection work in Java?

Answer:
Java’s Garbage Collector (GC) automatically removes objects that are no longer reachable to free up memory.

Process:

  • JVM marks unreachable objects during GC cycles.
  • These objects are then removed.
  • Methods like System.gc() can suggest a GC run, but it’s not guaranteed.

Garbage collection helps manage memory efficiently, avoiding manual deallocation.

Que 31. What is a static variable and method?

Answer:

  • Static variable: Shared among all instances of a class.
  • Static method: Belongs to the class, not instances, and can be called without creating an object.

Example:

class Demo {
  static int count = 0;
  static void print() {
    System.out.println("Count: " + count);
  }
}

Que 32. What is exception handling in Java?

Answer:
Exception handling deals with runtime errors gracefully using:

  • try: Code that might throw an exception.
  • catch: Code to handle the exception.
  • finally: Executes whether or not an exception occurs.
  • throw/throws: Used to explicitly throw or declare exceptions.

Example:

try {
  int x = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Cannot divide by zero.");
}

Que 33. What is the difference between throw and throws?

Answer:

KeywordPurposeUsage
throwUsed to explicitly throw an exceptionInside method block
throwsDeclares possible exceptions that a method can throwIn method signature

Example:

void method() throws IOException {
  throw new IOException("File not found");
}

Que 34. What is hierarchical inheritance in Java?

Answer:
Hierarchical inheritance occurs when multiple classes inherit from a single parent class. It helps reuse common code but can become complex if not managed well.

Que 35. What are wrapper classes in Java?

Answer:
Wrapper classes convert primitive types into objects.

PrimitiveWrapper Class
intInteger
charCharacter
booleanBoolean
doubleDouble

They are useful in collections (which store objects) and for utility methods.

Que 36. What is the difference between break and continue?

Answer:

  • break terminates the entire loop or switch.
  • continue skips the current iteration and proceeds to the next loop cycle.

Example:

for (int i = 0; i < 5; i++) {
  if (i == 2) continue;
  System.out.println(i);
}

Que 37. What is the THIS keyword?

Answer:
this refers to the current instance of the class.

Use Cases:

  • To refer to instance variables.
  • To call other constructors (this()).
  • To return the current object.

Example:

class Box {
  int length;
  Box(int length) {
    this.length = length;
  }
}

Que 38. What are Java packages and why are they used?

Answer:
A package is a namespace that organizes classes and interfaces.

Benefits:

  • Avoids name conflicts
  • Easier to maintain
  • Provides access protection

Example:

package com.company.project;

Built-in packages include java.util, java.io, java.lang, etc.

Que 39. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

ClassMutabilityThread-SafetyPerformance
StringImmutableYesSlowest
StringBuilderMutableNoFastest
StringBufferMutableYesSlower than StringBuilder

Use StringBuilder for single-threaded performance and StringBuffer in multithreaded scenarios.

Que 40. What is the default value of an instance variable?

Answer:
In Java, instance variables are automatically initialized to default values based on their type:

  • int, byte, short, long: 0
  • float, double: 0.0
  • boolean: false
  • char: '\u0000'
  • Object references: null

Local variables, however, must be initialized before use.

Java Interview Questions Freshers

Also Check: Top Coding Interview Questions

Core Java interview Questions and Answers for Experienced

We have already shared the basic Java interview questions, so now we are sharing advanced core Java interview questions for experienced candidates. These questions cover key Java concepts such as OOP, multithreading, memory, collections, and advanced programming techniques.

Que. 41 Explain the concept of immutability in Java and provide an example of an immutable class.

Answer: Immutability in Java means that once an object is created, its state cannot be modified. Any operation that appears to modify an immutable object will instead return a new object with the modified state. This offers several benefits, including thread safety, easier caching, and improved security.

To create an immutable class:

  • Declare the class as final to prevent extension.
  • Make all fields private and final.
  • Do not provide setter methods.

For mutable object fields, initialize them with a deep copy in the constructor and return deep copies from getter methods.

Example:

public final class ImmutablePoint {
    private final int x;
    private final int y;

    public ImmutablePoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public ImmutablePoint translate(int dx, int dy) {
        return new ImmutablePoint(this.x + dx, this.y + dy);
    }

    @Override
    public String toString() {
        return "ImmutablePoint{" +
               "x=" + x +
               ", y=" + y +
               '\'' + 
               '}';
    }
}

42. What is the use of “transient” keyword in Java?

Answer:
The transient keyword is used to prevent serialization of a variable.

transient int tempValue;

When an object is serialized, tempValue is skipped.

43. What is the difference between HashMap and ConcurrentHashMap?

Answer:

FeatureHashMapConcurrentHashMap
Thread-safeNoYes
Allows null keysOne null keyNo null key allowed
PerformanceFaster (single-threaded)Better in multi-threaded environments

44. Which string class should you use for thread-safe operations in Java?

Answer: Use StringBuffer for thread-safe string manipulations, as it is synchronized. However, it’s slower than StringBuilder, which is suitable for single-threaded scenarios.

45. What are autoboxing and unboxing in Java?

Answer:
Autoboxing is the automatic conversion of primitive types to wrapper classes. Unboxing is the reverse. For example, int to Integer and vice versa.

46. How does Java handle memory management?

Answer:

  • Managed by JVM
  • Memory areas include heap, stack, method area
  • Garbage collector reclaims memory of unused objects
  • Developers can request GC with System.gc() (but not guaranteed)

47. What is the difference between ArrayList and Vector?

Answer:

FeatureArrayListVector
Thread-SafeNoYes
PerformanceFasterSlower (synchronized)
Growth PolicyIncreases 50%Doubles in size

48. What is method hiding in Java?

Answer:
Method hiding happens when a static method in a subclass has the same signature as in the parent class. It does not override but hides the superclass method.

49. What is the difference between final, finally, and finalize()?

Answer:

  • final: restricts inheritance or changes
  • finally: block always executed after try-catch
  • finalize(): called by GC before destroying object (deprecated)

50. What is the role of the “volatile” keyword?

Answer:
Ensures visibility of changes made by one thread to other threads. It prevents caching of variables.

51. What is the difference between Abstract Class and Interface in Java 8 and later?

Answer:

FeatureAbstract ClassInterface (Java 8+)
Method TypesAbstract and concreteAbstract, default, static
Multiple InheritanceNot supportedSupported
ConstructorAllowedNot allowed

52. How do you handle thread deadlock in Java?

Answer:

  • Avoid nested locks
  • Use tryLock() with timeout
  • Use lock ordering
  • Detect using thread dumps and tools like VisualVM

53. What are functional interfaces?

Answer:
An interface with only one abstract method. Used in lambda expressions.

Example:

@FunctionalInterface
interface MyFunc {
  void execute();
}

54. What is the Stream API in Java?

Answer:
Introduced in Java 8 to process collections using a declarative style.

Example:

list.stream().filter(x -> x > 10).forEach(System.out::println);

55. What is the difference between HashSet and TreeSet?

Answer:

FeatureHashSetTreeSet
OrderingUnorderedSorted (natural or comparator)
PerformanceFaster (O(1))Slower (O(log n))
NullAllows one nullDoes not allow null

56. What is immutability and how can you create an immutable class?

Answer:
Immutable class cannot be changed once created.

Steps:

  • Make class final
  • Make fields private final
  • No setters
  • Initialize via constructor
  • Return copies of mutable objects

57. How does Java support multi-threading?

Answer:

  • By extending Thread or implementing Runnable
  • Java provides ExecutorService, Callable, Future for advanced concurrency
  • Thread lifecycle: New, Runnable, Running, Blocked, Terminated

38. What is reflection in Java?

Answer:
Reflection allows inspection and modification of classes, fields, and methods at runtime.

Example:

Class<?> cls = Class.forName("MyClass");
Method m = cls.getMethod("myMethod");
m.invoke(obj);

59. What are the types of class loaders in Java?

Answer:

  • Bootstrap ClassLoader
  • Extension ClassLoader
  • System ClassLoader
  • Custom ClassLoader (user-defined)

60. What are annotations in Java?

Answer:
Annotations provide metadata about the code. Common ones:

  • @Override
  • @Deprecated
  • @FunctionalInterface
  • Custom annotations can be created using @interface

Also Check: Java Interview Questions for Experienced

61. Describe the purpose and usage of Java Annotations, including custom annotations.

Answer: Java Annotations are metadata that can be added to Java source code. They provide information about the code but do not directly affect the execution of the code they annotate. Annotations are used for various purposes, such as:

Compiler instructions: @Override, @SuppressWarnings

  • Runtime processing: Used by frameworks like Spring or Hibernate for configuration.
  • Code generation: Tools can use annotations to generate boilerplate code.

Built-in Annotations:

  • @Override: Indicates that a method overrides a method in a superclass.
  • @Deprecated: Marks a program element as deprecated, indicating it should no longer be used.
  • @SuppressWarnings: Suppresses compiler warnings.
  • @FunctionalInterface: Indicates that an interface is a functional interface (has exactly one abstract method).

Custom Annotations: You can define your own annotations using the @interface keyword. They are often used to create custom metadata for frameworks or specific application logic.

Example of a custom annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) // Available at runtime via reflection
@Target(ElementType.METHOD)       // Can be applied to methods
public @interface LogExecution {
    String value() default ""; // An element with a default value
}

Usage of the custom annotation:

public class MyService {
    @LogExecution("Processing data")
    public void processData() {
        // ... method logic ...
    }
}

62. Explain the concept of method overriding vs method overloading in Java.

Answer:

Method Overloading (Compile-time polymorphism):

  • Same method name with different parameters (number, type, or order)
  • Occurs within the same class
  • Return type can be different but cannot be the only difference
  • Resolved at compile time

Method Overriding (Runtime polymorphism):

  • Child class provides specific implementation of parent class method
  • Same method signature (name, parameters, return type)
  • Uses @Override annotation
  • Resolved at runtime based on actual object type

Example:

// Overloading
class Calculator {
    public int add(int a, int b) { return a + b; }
    public double add(double a, double b) { return a + b; }
}

// Overriding
class Animal {
    public void makeSound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
    @Override
    public void makeSound() { System.out.println("Woof!"); }
}

63. What are the key differences between ArrayList and LinkedList? When would you use each?

Answer:

ArrayList:

  • Backed by dynamic array
  • Fast random access O(1) using index
  • Slower insertion/deletion in middle O(n) due to shifting
  • Better for read-heavy operations
  • Less memory overhead per element

LinkedList:

  • Backed by doubly linked list
  • Slow random access O(n) – must traverse from head/tail
  • Fast insertion/deletion O(1) if you have reference to node
  • Better for frequent insertions/deletions
  • More memory overhead due to node pointers

Use Cases:

  • ArrayList: When you need frequent random access, iteration, or size is relatively stable
  • LinkedList: When you frequently insert/delete elements at beginning/middle, or implement queue/deque

Performance Comparison:

list.get(index);        // O(1)
list.add(element);      // O(1) amortized
list.add(index, elem);  // O(n)

// LinkedList - good for  
list.addFirst(element); // O(1)
list.removeFirst();     // O(1)
list.get(index);        // O(n)

Scenario-Based Java Multithreading Interview Questions

Now its time to take a look on Scenario Based Java Multithreading Interview Questions crafted for practical understanding. These questions gradually increase in difficulty and focus on real-world problem-solving, synchronization, concurrency utilities, and thread lifecycle management.

64. You have two threads printing numbers from 1 to 10. How do you ensure the threads take turns?

Answer:
Use synchronized blocks and a shared lock object with wait() and notify() to alternate between threads.

65. A shared counter is updated by multiple threads, but the final count is inconsistent. What would you do?

Answer:
Synchronize the method or use AtomicInteger to make the counter thread-safe.

AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();

66. You want to stop a running thread on a button click. How do you do that safely?

Answer:
Use a volatile boolean flag to control thread execution.

volatile boolean running = true;

public void run() {
  while (running) {
    // work
  }
}

67. A thread must wait until another thread completes a task. Which approach do you use?

Answer:
Use Thread.join() or CountDownLatch.

Thread t = new Thread(task);
t.start();
t.join();

68. How do you ensure only one thread can access a critical section in a high-load environment?

Answer:
Use ReentrantLock for finer control compared to synchronized.

Lock lock = new ReentrantLock();
lock.lock();
try {
  // critical section
} finally {
  lock.unlock();
}

69. You have to process 10 tasks in parallel and then combine the results. How do you design it?

Answer:
Use ExecutorService with invokeAll() or CompletableFuture.allOf() to run tasks in parallel and wait for completion.

70. Your application is experiencing deadlock in production. How would you identify and fix it?

Answer:

  • Use thread dump analysis
  • Avoid nested locks or use consistent lock ordering
  • Prefer tryLock() with timeout to avoid blocking

71. How do you implement a producer-consumer scenario using Java’s concurrent utilities?

Answer:
Use BlockingQueue to decouple producers and consumers.

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
queue.put(1);   // producer
queue.take();   // consumer

72. You need to schedule a task every 5 seconds. What Java feature do you use?

Answer:
Use ScheduledExecutorService.

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);

73. A method updates multiple shared resources. How do you avoid data inconsistency without blocking all threads?

Answer:
Use fine grained locking or StampedLock to lock only the necessary resources, allowing higher concurrency with data safety.

Java Automation Testing interview Questions and Answers

Next questions are focused on automation testing, progressing from foundational to moderately advanced concepts.

74. What are the benefits of using Java in automation testing?

Answer:

  • Strong OOP support for reusable test components
  • Rich ecosystem (Selenium, TestNG, JUnit, Maven)
  • Robust exception handling
  • Readability and maintainability
  • Strong community support
Java Interview Questions Answers

Also Check: Java OOPs Interview Questions and Answers

75. How do you locate web elements using Selenium WebDriver in Java?

Answer:
Use methods like findElement() with locators such as:

driver.findElement(By.id("username"));
driver.findElement(By.xpath("//input[@name='email']"));
driver.findElement(By.cssSelector(".btn-primary"));

76. How do you handle synchronization issues in Selenium?

Answer:
Use waits:

  • Implicit Wait: Waits globally
  • Explicit Wait: Waits for a specific condition
  • Fluent Wait: Custom polling and exceptions

Example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));

77. What is the difference between Assert and Verify in test automation?

Answer:

FeatureAssertVerify
Stops execution on failureYesNo
Common inJUnit/TestNGCustom logging logic
ExampleAssert.assertTrue(condition)if(condition){ log success; } else { log failure; }

78. What is a Page Object Model in Java automation testing?

Answer:
Page Object Model (POM) is a design pattern that creates separate classes for each page of the application. It helps:

  • Improve maintainability
  • Reduce code duplication
  • Enhance readability

Example:

public class LoginPage {
  WebDriver driver;
  @FindBy(id="username") WebElement username;
  @FindBy(id="password") WebElement password;

  public void login(String user, String pass) {
    username.sendKeys(user);
    password.sendKeys(pass);
  }
}

79. How do you run your Selenium tests in parallel using Java?

Answer:

  • Use TestNG with parallel="tests" in testng.xml
  • Use @DataProvider with parallel=true
  • Use thread-safe WebDriver setup (ThreadLocal or WebDriverManager)

80. How do you handle file uploads in Selenium using Java?

Answer:
Use sendKeys() on file input elements.

WebElement upload = driver.findElement(By.id("file"));
upload.sendKeys("C:\\Users\\file.png");

If native OS dialog is involved, use tools like Robot class or AutoIt.

81. What is the role of Maven in Java automation testing?

Answer:

  • Dependency management
  • Build automation
  • Integration with TestNG, JUnit
  • Organizes project with standard structure

Example pom.xml snippet:

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.0.0</version>
</dependency>

82. How do you take a screenshot in Selenium using Java?

Answer:
Use TakesScreenshot interface.

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));

83. How do you design a test automation framework in Java?

Answer:
Framework components may include:

  • TestNG/JUnit for test execution
  • POM for structure
  • Utility classes for common actions
  • Logging with Log4j or ExtentReports
  • Data-Driven Testing using Excel, CSV, or DB
  • Build tools like Maven or Gradle
  • CI integration with Jenkins or GitHub Actions

Que 84. What is Java’s role in Selenium automation?

Answer:
Java is one of the most widely used languages for writing Selenium test scripts. It provides strong object-oriented features, rich libraries, and integration with tools like TestNG, Maven, and Jenkins, making it ideal for scalable test automation frameworks.

Que 85. What is the Page Object Model (POM) in Selenium using Java?

Answer:
Page Object Model is a design pattern that creates an object repository for web UI elements. Each web page is represented as a Java class, and the elements on the page are defined as variables. Actions are defined as methods. It improves test maintenance and code reusability.

Que 86. How do you handle dynamic web elements in Java Selenium?

Answer:
Dynamic elements can be handled using:

  • Relative XPath or CSS selectors
  • Explicit waits (WebDriverWait) to ensure elements are present or clickable
  • Java string manipulation for constructing XPath dynamically
  • Using regular expressions with XPath functions like contains(), starts-with()

Que 87. What is TestNG and why is it used in Java automation?

Answer:
TestNG is a testing framework inspired by JUnit. It supports annotations, grouping, sequencing, parameterization, data-driven testing, and generating detailed reports. It’s widely used for managing test execution in Java-based Selenium projects.

Que 88. How do you use waits in Selenium with Java?

Answer:
Selenium provides three types of waits:

  • Implicit Wait: Waits for a specified time before throwing NoSuchElementException.
  • Explicit Wait: Waits for a specific condition to occur before proceeding.
  • Fluent Wait: Defines the maximum time to wait and polling frequency.

Example using Explicit Wait:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

Que 89. How is exception handling done in automation scripts?

Answer:
Java’s try-catch-finally block is used to catch and handle exceptions like NoSuchElementException, TimeoutException, and ElementNotInteractableException. Handling these ensures scripts don’t fail unexpectedly and helps with debugging.

Que 90. What is the difference between findElement() and findElements()?

Answer:

MethodDescription
findElement()Returns the first matching element. Throws exception if not found.
findElements()Returns a list of all matching elements. Returns an empty list if none found.

Que 91. How do you perform cross-browser testing using Selenium in Java?

Answer:
You can configure different WebDriver instances based on the browser:

WebDriver driver;
if (browser.equalsIgnoreCase("chrome")) {
    driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("firefox")) {
    driver = new FirefoxDriver();
}

You can also use tools like Selenium Grid or cloud platforms (e.g., BrowserStack).

Que 92. What is Data-Driven Testing and how is it implemented in Java?

Answer:
Data-Driven Testing (DDT) separates test logic from test data. In Java, it can be implemented using:

  • @DataProvider annotation in TestNG
  • Reading data from external files like Excel (via Apache POI), CSV, or databases

This allows testing with multiple input sets without rewriting code.

Que 93. How do you handle alerts and pop-ups in Selenium with Java?

Answer:
Use the Alert interface:

Alert alert = driver.switchTo().alert();
alert.accept(); // or alert.dismiss(), alert.getText()

For authentication pop-ups, use the username and password in the URL or handle it via external tools (like AutoIT or Robot class).

Que 94. What is the difference between Assert and Verify in Java TestNG?

Answer:

FeatureAssertVerify
BehaviorStops execution on failureLogs the failure, continues test
Use CaseCritical checksNon-critical validations

Assert is built into TestNG, while Verify can be custom-implemented using try-catch blocks.

Que 95. How do you capture a screenshot in Selenium with Java?

Answer:

TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(\"path/to/save.png\"));

Used for debugging failed test cases or documentation purposes.

Que 96. What is Selenium Grid and how do you use it in Java?

Answer:
Selenium Grid allows parallel test execution across multiple machines and browsers. You configure a hub and register nodes. Java interacts with it via RemoteWebDriver:

WebDriver driver = new RemoteWebDriver(new URL(\"http://localhost:4444/wd/hub\"), capabilities);

Que 97. How do you manage test dependencies in Java automation projects?

Answer:
Dependencies are managed using Maven or Gradle. These tools handle libraries like Selenium, TestNG, Apache POI, etc., using pom.xml or build.gradle.

Que 98. What are locators in Selenium? Which ones are preferred?

Answer:
Locators identify elements on a web page. Types include:

  • ID
  • Name
  • Class Name
  • XPath
  • CSS Selector
  • Link Text

Preferred: ID and CSS for speed and reliability. XPath is flexible but slower.

Que 99. How do you verify if a checkbox is selected in Selenium using Jav

Answer:

WebElement checkbox = driver.findElement(By.id(\"check1\"));
boolean isChecked = checkbox.isSelected();

You can also use click() to toggle its state.

Que 100. How do you generate test reports in Java-based Selenium frameworks?

Answer:
Popular options include:

  • TestNG Reports: Auto-generated HTML reports.
  • ExtentReports: Customizable, visually rich reports.
  • Allure Reports: Integrates with CI tools and shows history.

Reports give insights into passed/failed tests, screenshots, logs, and performance.

Also Check: Java Selenium Interview Questions

Java Interview Questions PDF

We’ve shared various types of questions, and now we’re adding PDF file of that, so you can prepare offline without any ads distractions.

FAQs: Java interview

What is the role of a Java developer in a company?

A Java developer is responsible for designing, developing, and maintaining software applications using the Java programming language. Their role often includes writing clean code, debugging errors, working with databases, using frameworks like Spring or Hibernate, and collaborating with other developers to build scalable applications.

What types of challenges do candidates face during Java interviews?

Candidates often face challenges like answering complex coding questions under time pressure, solving real-life technical scenarios, explaining core concepts like OOP, multithreading, and exception handling, and demonstrating practical knowledge of Java frameworks. Interviews may also include live coding rounds and technical problem-solving tasks.

Why is Java still in demand in 2025?

Java remains in demand because it’s widely used in enterprise software, banking systems, Android development, cloud applications, and backend services. Its stability, scalability, and strong community support make it a preferred choice for many organizations, keeping the demand for skilled Java developers high.

What technical skills should candidates have for Java jobs?

Candidates should be skilled in Java programming, object-oriented programming (OOP), data structures, algorithms, working with databases (SQL), using frameworks like Spring Boot and Hibernate, REST APIs, and basic knowledge of version control systems like Git. Knowing software development principles like Agile or DevOps is often a plus.

What is the average salary for Java developers in the USA?

The average salary for a Java developer in the USA typically ranges from $80,000 to $130,000 per year, depending on experience level, location, and company size. Senior Java developers or those working in specialized industries may earn salaries above $150,000 annually.

Which top companies hire Java developers?

Many leading companies hire Java professionals regularly. These include Amazon, Google, Microsoft, IBM, Oracle, Accenture, TCS, Infosys, Cognizant, JPMorgan Chase, and Wipro, among others. Both startups and large enterprises look for skilled Java developers for various backend and full-stack roles.

How can preparing for Java interviews help in career growth?

Preparing for Java interviews improves your coding skills, deepens your understanding of core concepts, and boosts your confidence during technical discussions. Well-prepared candidates have better chances of getting hired by top companies, negotiating higher salaries, and progressing into senior or specialized Java development roles.

Conclusion

In the article above, we have shared a wide range of Java interview questions and answers, covering everything from basic questions for freshers to core Java questions for experienced candidates, along with real-world scenario-based questions to help you prepare better.

We have also provided a PDF, so you can easily study offline and prepare anytime at your convenience. Best wishes for your upcoming interview.

Tags: java interview questions for freshers pdf, java viva questions and answers pdf, 1600+ java interview questions pdf, core java interview questions pdf

Similer Interview Guides:

Python Interview QuestionsPHP Interview Questions
Java Selenium Interview QuestionsFull Stack Developer Interview Questions