Java Interview Questions for Testers

Beginner Level Java Interview Questions for Testers

  1. What is Java?
    • Answer: Java is a high-level, object-oriented programming language known for its platform independence.
  2. Explain the main features of Java.
    • Answer: Features include platform independence, object-oriented, simple syntax, robustness, and automatic memory management.
  3. What is the difference between JDK and JRE?
    • Answer: JDK (Java Development Kit) contains tools for development, while JRE (Java Runtime Environment) is used for running Java applications.
  4. What is the role of the public static void main(String[] args) method in Java?
    • Answer: It’s the entry point of a Java program; execution starts from this method.
  5. How is Java platform-independent?
    • Answer: Java code is compiled into an intermediate form (bytecode) that runs on the Java Virtual Machine (JVM), making it platform-independent.
  6. What is a variable in Java?
    • Answer: A variable is a container that holds data values.
  7. What is the difference between int and Integer in Java?
    • Answer: int is a primitive data type, while Integer is a wrapper class for int.
  8. Explain the this keyword in Java.
    • Answer: this refers to the current instance of the object in which it is used.
  9. What is the purpose of the new keyword in Java?
    • Answer: new is used to create an instance of a class or to allocate memory for an object.
  10. How are comments written in Java?
    • Answer: Single-line comments start with //, and multi-line comments are enclosed between /* and */.
  11. What is the difference between == and .equals() in Java?
    • Answer: == checks for reference equality, while .equals() checks for content equality for objects.
  12. What is a constructor in Java?
    • Answer: A constructor is a special method used to initialize objects.
  13. How do you declare a constant in Java?
    • Answer: Using the final keyword.
  14. What is the purpose of the super keyword?
    • Answer: super is used to call the superclass’s methods, constructors, and access superclass fields.
  15. What is a Java package?
    • Answer: A package is a group of related classes and interfaces.
  16. Explain the difference between float and double in Java.
    • Answer: float is a 32-bit single-precision type, and double is a 64-bit double-precision type.
  17. What is the NullPointerException in Java?
    • Answer: It occurs when an application attempts to access an object with a null reference.
  18. How is an ArrayList different from an array in Java?
    • Answer: An ArrayList can dynamically resize, while an array has a fixed size.
  19. What is the use of the static keyword in Java?
    • Answer: It is used to create class-level variables and methods.
  20. Explain method overloading in Java.
    • Answer: Method overloading allows a class to have multiple methods with the same name but different parameters.
  21. How do you handle exceptions in Java?
    • Answer: By using try, catch, finally, and throw statements.
  22. What is the purpose of the break statement in Java?
    • Answer: It is used to terminate the loop or switch statement.
  23. What is the default value of the char data type in Java?
    • Answer: The default value is ‘\u0000’ (null character).
  24. What is the difference between String and StringBuilder?
    • Answer: String is immutable, while StringBuilder is mutable.
  25. How do you convert a string to an integer in Java?
    • Answer: Using Integer.parseInt() or Integer.valueOf().
  26. What is the purpose of the return statement in Java?
    • Answer: It is used to exit a method and return a value.
  27. Explain the switch statement in Java.
    • Answer: switch is a control statement used to select one of many code blocks to be executed.
  28. What is the instanceof operator used for in Java?
    • Answer: It is used to test whether an object is an instance of a particular class or interface.
  29. How do you implement inheritance in Java?
    • Answer: By using the extends keyword.
  30. What is the purpose of the interface keyword in Java?
    • Answer: It is used to declare an interface.
  31. How do you implement polymorphism in Java?
    • Answer: By using method overloading and method overriding.
  32. What is the difference between while and do-while loops in Java?
    • Answer: while checks the condition before the loop, while do-while checks after the loop.
  33. What is the purpose of the throw keyword in Java?
    • Answer: It is used to explicitly throw an exception.
  34. Explain the concept of encapsulation in Java.
    • Answer: Encapsulation is the bundling of data and methods that operate on that data within a single unit (class).
  35. What is the purpose of the finally block in Java?
    • Answer: It is used to ensure that a block of code is always executed, whether an exception is thrown or not.
  36. How is a for-each loop different from a regular for loop?
    • Answer: for-each is used to iterate over elements of an array or collection, while a regular for loop is more general-purpose.
  37. What is the difference between public, private, protected, and default access modifiers in Java?
    • Answer: They control the visibility of classes, methods, and fields. public is accessible from anywhere, private only within the class, protected within the package and subclasses, and the default (no modifier) within the package.
  38. What is the Math.random() method used for in Java?
    • Answer: It returns a random number between 0 (inclusive) and 1 (exclusive).
  39. How is try-with-resources used in Java?
    • Answer: It is used to automatically close resources like files or sockets after they are no longer needed.
  40. What is the purpose of the super() keyword in a constructor?
    • Answer: It is used to call the constructor of the superclass.
  41. How do you convert an int to a String in Java?
    • Answer: By using String.valueOf() or Integer.toString().
  42. Explain the && and || operators in Java.
    • Answer: && is the logical AND operator, and || is the logical OR operator.
  43. What is the difference between a LinkedList and an ArrayList in Java?
    • Answer: ArrayList uses a dynamic array, while LinkedList uses a doubly-linked list.
  44. How do you declare a constant in an interface in Java?
    • Answer: By using the final keyword.
  45. What is the purpose of the continue statement in Java?
    • Answer: It is used to skip the rest of the code inside a loop for the current iteration.
  46. Explain the transient keyword in Java.
    • Answer: It is used to indicate that a field should not be serialized.
  47. What is the purpose of the break statement in a switch block?
    • Answer: It is used to terminate the switch statement.
  48. How do you implement multiple inheritance in Java?
    • Answer: Java does not support multiple inheritance directly; it is achieved using interfaces.
  49. What is the Thread.sleep() method used for in Java?
    • Answer: It suspends the current thread for a specified amount of time.
  50. What is the purpose of the StringBuffer class in Java?
    • Answer: It is used to represent characters that can be modified (mutable sequence of characters).

Intermediate Level Java Interview Questions for Testers

  1. Explain the concept of method overriding in Java.
    • Answer: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
  2. What are checked and unchecked exceptions in Java?
    • Answer: Checked exceptions are checked at compile-time, while unchecked exceptions are checked at runtime.
  3. Describe the Singleton design pattern in Java.
    • Answer: Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
  4. What is the purpose of the volatile keyword in Java?
    • Answer: volatile keyword is used to indicate that a variable’s value may be changed by multiple threads simultaneously.
  5. Explain the difference between HashMap and Hashtable in Java.
    • Answer: Both are used to store key-value pairs, but Hashtable is synchronized, while HashMap is not.
  6. What is the Observer design pattern in Java?
    • Answer: The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
  7. Describe the concept of garbage collection in Java.
    • Answer: Garbage collection is the process of automatically identifying and reclaiming memory occupied by objects that are no longer in use.
  8. What is the purpose of the equals() and hashCode() methods in Java?
    • Answer: equals() is used to compare the contents of two objects, and hashCode() returns a hash code value for an object.
  9. Explain the difference between poll() and remove() methods in the Queue interface.
    • Answer: Both methods remove and return the head of the queue, but poll() returns null if the queue is empty, while remove() throws an exception.
  10. What is the super keyword used for in a method?
    • Answer: super is used to invoke the superclass method, constructor, or field.
  11. How does the this() constructor call work in Java?
    • Answer: It is used to invoke the current class constructor.
  12. Explain the concept of method overloading in Java.
    • Answer: Method overloading occurs when a class has multiple methods with the same name but different parameter types.
  13. What is the Thread class, and how is it different from Runnable in Java?
    • Answer: Thread is a class representing a thread of execution, while Runnable is an interface that provides a way to create a thread.
  14. How do you implement a static block in Java?
    • Answer: Using a static block, which is executed when the class is loaded into memory.
  15. Explain the synchronized keyword in Java.
    • Answer: synchronized is used to control access to the critical section of code by allowing only one thread to execute it at a time.
  16. What is the Comparator interface used for in Java?
    • Answer: Comparator interface is used to define a custom order for objects.
  17. Describe the StringBuilder class in Java.
    • Answer: StringBuilder is a mutable sequence of characters, and it is more efficient than String when performing concatenation operations.
  18. What is the purpose of the @Override annotation in Java?
    • Answer: @Override is used to indicate that a method in a subclass is intended to override a method in its superclass.
  19. How does the transient keyword affect object serialization in Java?
    • Answer: It indicates that a field should not be serialized.
  20. Explain the AutoCloseable interface in Java.
    • Answer: AutoCloseable is an interface implemented by classes whose instances can be automatically closed when used with the try-with-resources statement.
  21. Describe the Observer design pattern in Java.
    • Answer: The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
  22. What is the purpose of the instanceof operator in Java?
    • Answer: It is used to test whether an object is an instance of a particular class or interface.
  23. Explain the difference between finalize() and dispose() methods in Java.
    • Answer: finalize() is a method in the Object class that is called by the garbage collector before an object is reclaimed, while dispose() is a method used to release resources explicitly.
  24. How do you create a custom exception in Java?
    • Answer: By extending the Exception class or one of its subclasses.
  25. What is the purpose of the import statement in Java?
    • Answer: It is used to include classes from other packages in your program.
  26. Describe the Lambda expression in Java.
    • Answer: Lambda expressions provide a concise way to express instances of single-method interfaces (functional interfaces).
  27. How does the clone() method work in Java?
    • Answer: The clone() method creates and returns a copy of the object.
  28. What is the super() constructor call used for?
    • Answer: It is used to call the constructor of the superclass.
  29. Explain the concept of abstraction in Java.
    • Answer: Abstraction is the process of hiding the implementation details and showing only the functionality to the user.
  30. What is the volatile keyword used for in Java?
    • Answer: volatile keyword is used to indicate that a variable’s value may be changed by multiple threads simultaneously.
  31. Describe the finally block in Java.
    • Answer: The finally block contains code that is always executed, regardless of whether an exception is thrown or not.
  32. What is the purpose of the assert statement in Java?
    • Answer: It is used for debugging purposes and to test assumptions about the program.
  33. Explain the concept of polymorphism in Java.
    • Answer: Polymorphism allows objects of different types to be treated as objects of a common type.
  34. How does the Comparator interface work in sorting collections in Java?
    • Answer: The Comparator interface provides a way to define a custom order for objects when sorting collections.
  35. What is the purpose of the super keyword in Java?
    • Answer: super is used to refer to the superclass’s fields, methods, and constructors.
  36. How do you implement multi-threading in Java?
    • Answer: By extending the Thread class or implementing the Runnable interface.
  37. Explain the try-with-resources statement in Java.
    • Answer: The try-with-resources statement is used to automatically close resources like files or sockets after they are no longer needed.
  38. Describe the Enum in Java.
    • Answer: An Enum is a special data type that allows a variable to have one of a set of predefined constants.
  39. What is the purpose of the @FunctionalInterface annotation in Java?
    • Answer: It indicates that an interface is intended to be a functional interface and can be used with lambda expressions.
  40. Explain the Comparable interface in Java.
    • Answer: The Comparable interface is used to define a natural order for a class so that instances of the class can be sorted.
  41. How do you implement a shallow copy and a deep copy in Java?
    • Answer: Shallow copy is achieved using the clone() method, and deep copy involves creating a new object and copying the contents.
  42. What is the purpose of the static keyword in Java?
    • Answer: It is used to create class-level variables and methods.
  43. Explain the Proxy design pattern in Java.
    • Answer: The Proxy pattern involves a surrogate or placeholder object controlling access to another object.
  44. How does the break statement work in a loop in Java?
    • Answer: The break statement is used to terminate the loop or switch statement.
  45. What is the Object class in Java, and what methods does it provide?
    • Answer: The Object class is the root class for all Java classes and provides methods like toString(), equals(), and hashCode().
  46. Explain the concept of method chaining in Java.
    • Answer: Method chaining involves calling multiple methods in a single line, where each method returns an object.
  47. What is the purpose of the IdentityHashMap class in Java?
    • Answer: IdentityHashMap uses reference equality to compare keys, unlike other map implementations that use equals().
  48. How do you implement a generic class in Java?
    • Answer: By using the <T> syntax to represent a generic type.
  49. What is the purpose of the try block in exception handling in Java?
    • Answer: The try block contains code that may throw an exception.
  50. Explain the Iterator interface in Java.
    • Answer: The Iterator interface provides a way to iterate over a collection of objects.

Advanced Level Java Interview Questions for Testers

  1. What is the difference between HashMap and ConcurrentHashMap in Java?
    • Answer: ConcurrentHashMap allows multiple threads to read and write concurrently, providing better performance in a multi-threaded environment.
  2. Explain the concept of a lambda expression in Java. Provide an example of its usage.
    • Answer: A lambda expression is a concise way to represent an anonymous function. Example: (a, b) -> a + b
  3. Describe the Java Memory Model (JMM) and its importance in multi-threading.
    • Answer: JMM defines the rules and guidelines for how Java programs access and manipulate shared data in a multi-threaded environment.
  4. What are the benefits and drawbacks of using the synchronized keyword for achieving thread safety?
    • Answer: Benefits include simplicity, but drawbacks include decreased performance due to contention.
  5. Explain the concept of the Observer design pattern and provide an example of its implementation in Java.
    • Answer: The Observer pattern defines a one-to-many dependency between objects. Example: The java.util.Observable class.
  6. What is the java.util.function package in Java, and how does it relate to functional programming?
    • Answer: The java.util.function package provides functional interfaces for use with lambda expressions and method references.
  7. Describe the try-with-resources statement in detail.
    • Answer: try-with-resources automatically closes resources (like files or sockets) after they are no longer needed.
  8. Explain the concept of lazy initialization and how it can be implemented in Java.
    • Answer: Lazy initialization delays the creation of an object until it is actually needed, often achieved using the double-checked locking idiom.
  9. What is the purpose of the CompletableFuture class in Java, and how does it facilitate asynchronous programming?
    • Answer: CompletableFuture is used for asynchronous programming, providing a way to perform operations asynchronously and then combine their results.
  10. Explain the concept of the java.util.stream package and how it supports functional-style operations on streams of elements.
    • Answer: The java.util.stream package provides a functional approach to process sequences of elements, supporting operations like map, filter, and reduce.
  11. What is the purpose of the ReentrantLock class in Java, and how does it differ from the synchronized keyword?
    • Answer: ReentrantLock provides a more flexible locking mechanism than synchronized and allows for more complex synchronization patterns.
  12. Explain the concept of the ForkJoinPool in Java and its role in parallel processing.
    • Answer: ForkJoinPool is designed for parallel processing, particularly for divide-and-conquer algorithms using the Fork-Join framework.
  13. Describe the concept of the Decorator design pattern and provide an example of its implementation in Java.
    • Answer: The Decorator pattern allows behavior to be added to an individual object, either statically or dynamically. Example: The java.io package.
  14. What is the purpose of the java.util.concurrent package in Java, and how does it enhance concurrent programming?
    • Answer: The java.util.concurrent package provides high-level concurrency utilities, such as ExecutorService and ConcurrentMap.
  15. Explain the concept of the Reactive Programming paradigm and how it can be implemented in Java using libraries like Reactor or RxJava.
    • Answer: Reactive Programming is a programming paradigm focused on asynchronous data streams. Reactor and RxJava are libraries that provide tools for working with reactive streams in Java.
  16. Describe the concept of a WeakReference in Java and its use cases.
    • Answer: A WeakReference allows an object to be garbage-collected when there are no strong references to it.
  17. Explain the difference between the Stack and Heap memory areas in Java.
    • Answer: The Stack is used for local variables and method calls, while the Heap is used for object storage.
  18. What is the purpose of the java.nio package, and how does it improve I/O operations in Java?
    • Answer: The java.nio package provides a new I/O framework that supports non-blocking I/O operations and memory-mapped file I/O.
  19. Describe the concept of the Flyweight design pattern and provide an example of its implementation in Java.
    • Answer: The Flyweight pattern minimizes memory usage or computational expenses by sharing as much as possible with other similar objects. Example: The String pool in Java.
  20. Explain the concept of the PhantomReference class in Java and its use cases.
    • Answer: A PhantomReference allows an object to be finalized and reclaimed by the garbage collector after it has been collected.
  21. What is the purpose of the java.lang.instrument package in Java, and how is it used for bytecode manipulation?
    • Answer: The java.lang.instrument package provides services that allow Java programming agents to instrument programs running on the JVM, often used for profiling or monitoring.
  22. Describe the Builder design pattern and provide an example of its implementation in Java.
    • Answer: The Builder pattern separates the construction of a complex object from its representation. Example: StringBuilder in Java.
  23. What is the @FunctionalInterface annotation, and how does it relate to functional programming in Java?
    • Answer: The @FunctionalInterface annotation is used to ensure that an interface has only one abstract method, indicating it can be used as a functional interface for lambda expressions.
  24. Explain the concept of Java Virtual Machine (JVM) profiling and common tools used for it.
    • Answer: Profiling involves collecting and analyzing data about the execution of a program. Common tools include VisualVM, YourKit, and Java Mission Control.
  25. Describe the concept of the Service Provider Interface (SPI) in Java and how it facilitates extensibility.
    • Answer: SPI is a design pattern that allows an application to be extended with new functionality through the addition of new service providers without altering the existing code.
  26. What is the purpose of the LocalDate class in Java, and how does it improve date and time handling?
    • Answer: LocalDate is part of the Java Date and Time API, providing a date without time information, and facilitating easier date manipulation.
  27. Explain the concept of Method References in Java and provide examples of different types of method references.
    • Answer: Method references are a shorthand notation of a lambda expression to call a method. Types include static, instance, and constructor references.
  28. What is the purpose of the java.lang.reflect package in Java, and how is it used for runtime class manipulation?
    • Answer: The java.lang.reflect package provides classes and interfaces for obtaining reflective information about classes and objects.
  29. Describe the Adapter design pattern and provide an example of its implementation in Java.
    • Answer: The Adapter pattern allows incompatible interfaces to work together. Example: The ArrayAdapter in Android.
  30. Explain the concept of Aspect-Oriented Programming (AOP) in Java and how it can be implemented using frameworks like Spring AOP.
    • Answer: AOP is a programming paradigm that allows the separation of cross-cutting concerns from the core business logic. Spring AOP enables modularization of concerns like logging and transaction management.
  31. What is the purpose of the java.security package in Java, and how is it used for implementing security features?
    • Answer: The java.security package provides classes and interfaces for the Java security framework, including cryptography and access control.
  32. Describe the concept of ThreadLocal in Java and how it can be used for thread-specific storage.
    • Answer: ThreadLocal allows each thread to have its own copy of an object, preventing interference from other threads.
  33. Explain the concept of Method Handles in Java and how they differ from traditional reflection.
    • Answer: Method handles provide a way to perform high-performance method invocations in Java, often faster than traditional reflection.
  34. What is the purpose of the java.util.concurrent.atomic package in Java, and how does it provide atomic operations?
    • Answer: The java.util.concurrent.atomic package provides classes for atomic operations, ensuring that certain operations are performed atomically.
  35. Describe the Memento design pattern and provide an example of its implementation in Java.
    • Answer: The Memento pattern provides the ability to restore an object to its previous state. Example: Undo functionality in text editors.
  36. What is the VarHandle class in Java, and how does it relate to low-level concurrency operations?
    • Answer: VarHandle provides a way to perform atomic operations on variables in a low-level, efficient manner.
  37. Explain the concept of Functional Interfaces in Java and their role in supporting lambda expressions.
    • Answer: Functional Interfaces have a single abstract method and are eligible to be used as lambda expressions in Java.
  38. What is the purpose of the java.lang.instrument package in Java, and how is it used for bytecode manipulation?
    • Answer: The java.lang.instrument package provides services that allow Java programming agents to instrument programs running on the JVM, often used for profiling or monitoring.
  39. Describe the concept of Record in Java and how it simplifies the creation of immutable data classes.
    • Answer: A Record in Java is a special kind of class primarily used for immutable data modeling. It automatically generates methods like equals(), hashCode(), and toString().
  40. Explain the concept of CompletableFutures in Java and how they differ from Future objects.
    • Answer: CompletableFuture is an extension of Future that provides a more flexible and functional approach to asynchronous programming.
  41. What is the purpose of the ThreadMXBean interface in Java, and how is it used for monitoring and managing threads?
    • Answer: ThreadMXBean is part of the Java Management Extensions (JMX) API, providing access to thread-related metrics and operations.
  42. Describe the Mediator design pattern and provide an example of its implementation in Java.
    • Answer: The Mediator pattern defines an object that encapsulates how a set of objects interact. Example: GUI frameworks where components communicate through a mediator.
  43. Explain the concept of Value-based Classes in Java and how they differ from traditional classes.
    • Answer: Value-based classes are immutable, final, and have implementations of equals(), hashCode(), and toString() that are based solely on their state.
  44. What is the purpose of the java.util.function package in Java, and how does it support functional programming?
    • Answer: The java.util.function package provides functional interfaces that can be used with lambda expressions, allowing a more functional programming style in Java.
  45. Describe the Object.finalize() method in Java and its role in garbage collection.
    • Answer: The finalize() method is called by the garbage collector before an object is reclaimed, giving the object a chance to clean up resources.
  46. What is the java.lang.StackWalker class in Java, and how can it be used for stack walking?
    • Answer: StackWalker provides a mechanism for walking the stack trace of the current thread or a specified thread, allowing access to the frames of the stack.
  47. Explain the concept of the Exchanger class in Java and how it facilitates the exchange of data between two threads.
    • Answer: The Exchanger class provides a synchronization point at which threads can pair and swap elements within pairs, enabling efficient data exchange between them.
  48. What is the purpose of the java.util.concurrent.CopyOnWriteArrayList class in Java, and how does it differ from ArrayList in terms of thread safety?
    • Answer: CopyOnWriteArrayList is a thread-safe variant of ArrayList where all mutative operations (add, set, remove, etc.) are implemented by creating a new copy of the underlying array. It ensures thread safety without the need for explicit synchronization.
  49. Describe the concept of Immutable Objects in Java and explain why immutability is desirable in certain scenarios.
    • Answer: Immutable objects are objects whose state cannot be modified after they are created. Immutability is desirable in scenarios where thread safety, simplicity, and predictability are crucial. Immutable objects simplify reasoning about the code, reduce the need for synchronization, and are often more suitable for use as keys in hash-based data structures.
  50. Explain the concept of the java.lang.invoke package in Java and how it is used for dynamic method invocation.
    • Answer: The java.lang.invoke package provides a mechanism for dynamic method invocation, allowing the creation of method handles that can be invoked reflectively. It is particularly useful for building language runtime support, dynamic proxies, and other advanced invocation scenarios in Java.

Frequently used Inbuilt Java functions/packages by Java + Selenium Automation testers

Function/PackagePurpose/Description
java.util.ArraysProvides utility methods for working with arrays, including sorting and searching.
java.util.CollectionsContains static methods for operating on collections, like sorting and shuffling.
java.util.regexSupports regular expressions for pattern matching and string manipulation.
java.nio.fileOffers file and directory I/O operations, enhancing capabilities for file handling.
java.timeProvides classes for working with dates, times, and durations in a more modern way.
java.util.concurrentOffers utility classes for concurrent programming, including thread pools and locks.
java.netFacilitates networking operations, such as creating sockets and working with URLs.
javax.swingEnables the creation of graphical user interfaces (GUI) in Java applications.
junit.frameworkFramework for writing and running unit tests in Java.
TestNGTesting framework inspired by JUnit, supporting parallel test execution and more.
SeleniumWeb testing framework for automating web browsers. Supports various programming languages.
RestAssuredJava library for testing RESTful web services. Simplifies API testing.
Assert class (in org.junit.Assert or org.testng.Assert)Contains assertion methods for performing test validations.
MockitoMocking framework for creating and using mock objects for unit testing.
Log4jLogging framework for Java applications. Provides flexible and configurable logging.
Apache POILibrary for reading and writing Microsoft Office files (Excel, Word, PowerPoint).
JacksonLibrary for JSON processing in Java, including data binding and tree model.
java.util.PropertiesRepresents a persistent set of properties, often used for configuration settings.
java.util.concurrent.TimeUnitEnum representing time units, useful for managing timeouts and delays.
java.util.streamIntroduces the Stream API for processing sequences of elements in a functional style.
java.util.OptionalRepresents an optional value and helps avoid null pointer exceptions.
java.util.concurrent.ExecutorInterface for objects that execute submitted tasks asynchronously.
java.util.concurrent.ExecutorsFactory and utility methods for creating thread pools and executors.
java.util.concurrent.CountDownLatchSynchronization aid that allows one or more threads to wait until a set of operations completes.
java.util.concurrent.CyclicBarrierSynchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
java.util.concurrent.SemaphoreProvides a mechanism for controlling access to resources in a multi-threaded environment.
java.util.concurrent.ConcurrentHashMapConcurrent, thread-safe implementation of the Map interface.
java.util.concurrent.LinkedBlockingQueueA blocking queue that uses linked nodes. Commonly used in producer-consumer scenarios.
java.util.concurrent.TimeUnitEnum representing time units, often used with timeouts and delays.
java.text.SimpleDateFormatAllows formatting and parsing of dates and times according to a specified pattern.
java.util.loggingJava Logging API for logging messages from Java programs.
javax.xml.parsersProvides classes for parsing XML documents, useful in testing scenarios involving XML data.
javax.sqlJava Database Connectivity (JDBC) for database-related testing.
javax.mailJavaMail API for sending and receiving emails in testing scenarios.
org.apache.commons.lang3.StringUtilsProvides utility methods for working with strings, often used in testing assertions.
org.apache.commons.ioCommon I/O utilities, including file handling and input/output operations.
org.apache.http.clientApache HttpClient for making HTTP requests and testing RESTful APIs.
org.testng.annotationsTestNG annotations for configuring and customizing test methods and classes.
org.junit.jupiter.apiJUnit 5 annotations for writing tests with the JUnit testing framework.

Java Methods Cheatsheet : Most commonly used methods in various testing domains

DomainCommonly Used Methods
Assertions (JUnit/TestNG)assertEquals(expected, actual)
assertNotEquals(expected, actual)
assertTrue(condition)
assertFalse(condition)
assertNotNull(object)
assertNull(object)
String ManipulationcharAt(index)
length()
substring(start, end)
split(delimiter)
replace(oldChar, newChar)
toLowerCase()
toUpperCase()
trim()
File Handling (java.nio.file)Files.exists(path)
Files.isRegularFile(path)
Files.isDirectory(path)
Files.readAllLines(path)
Files.write(path, data)
Files.copy(source, target)
Files.move(source, target)
Date/Time (java.time)LocalDate.now()
LocalTime.now()
LocalDateTime.now()
LocalDate.of(year, month, day)
LocalTime.of(hour, minute, second)
Period.between(date1, date2)
Duration.between(time1, time2)
Collections FrameworkList.add(element)
List.get(index)
List.size()
Map.put(key, value)
Map.get(key)
Set.add(element)
Set.contains(element)
Collections.sort(list)
Collections.shuffle(list)
Concurrency (java.util.concurrent)ExecutorService.submit(Callable)
Future.get()
CountDownLatch.await()
CyclicBarrier.await()
Semaphore.acquire()
Semaphore.release()
AtomicInteger.incrementAndGet()
Lock.lock()
Lock.unlock()
Web Testing (Selenium)WebDriver.get(url)
WebDriver.findElement(By)
WebElement.click()
WebElement.sendKeys(text)
WebDriver.navigate().to(url)
WebDriver.quit()
API Testing (RestAssured)given().get(endpoint)
given().post(endpoint)
given().put(endpoint)
given().delete(endpoint)
expect().statusCode(code)
expect().body("key", equalTo(value))
Database Testing (JDBC)Connection.prepareStatement(sql)
Statement.executeQuery(sql)
ResultSet.next()
ResultSet.getString(column)
PreparedStatement.executeUpdate()
Mocking (Mockito)Mockito.mock(Class)
Mockito.when(mock.methodCall()).thenReturn(value)
Mockito.verify(mock).methodCall()
Mockito.verifyNoMoreInteractions(mock)
Logging (Log4j)Logger.debug(message)
Logger.info(message)
Logger.warn(message)
Logger.error(message)
Logger.fatal(message)
HTTP Requests (Apache HttpClient)HttpClient.newHttpClient()
HttpRequest.newBuilder().uri(uri).build()
HttpResponse.BodyHandlers.ofString()
client.send(request, HttpResponse.BodyHandlers.ofString())
XML Parsing (javax.xml.parsers)DocumentBuilderFactory.newDocumentBuilder()
builder.parse(inputStream)
element.getElementsByTagName(tagName)
node.getTextContent()
Email Handling (javax.mail)Session.getDefaultInstance(properties)
MimeMessage message = new MimeMessage(session)
message.setSubject(subject)
message.setText(content)
Transport.send(message)
Random Number GenerationRandom.nextInt()
ThreadLocalRandom.current().nextInt()
SecureRandom.getInstance("SHA1PRNG").nextInt()
System Properties and Environment VariablesSystem.getProperty("property")
System.getenv("variable")
Reflection (java.lang.reflect)Class.forName(className)
Class.getDeclaredMethods()
Method.invoke(object, args)
Field.get(object)
Constructor.newInstance(args)
Regular Expressions (java.util.regex)Pattern.compile(regex)
Matcher.matches()
Matcher.find()
Matcher.group()
JSON Processing (Jackson)ObjectMapper.writeValueAsString(obj)
ObjectMapper.readValue(json, Class)
Logging (java.util.logging)Logger.getLogger("loggerName")
Logger.log(Level, message)
Exception Handlingtry {...} catch (Exception e) {...}
throw new CustomException("message")
assertThrows(Exception.class, () -> methodThrowingException())
Math OperationsMath.abs(value)
Math.max(a, b)<br>- Math.min(a, b)
Math.pow(base, exponent)
Math.sqrt(value)
Thread ManagementThread.sleep(milliseconds)
Thread.currentThread().getId()
Thread.currentThread().getName()
Thread.yield()<br>- Thread.join()
Thread.interrupt()
HTTP Cookies (javax.servlet.http)HttpServletRequest.getCookies()
HttpServletResponse.addCookie(cookie)
JUnit 5 AssertionsassertAll(executables)
assertTimeout(duration, executable)
assertTimeoutPreemptively(duration, executable)
assertThrows(exceptionType, executable)
Scroll to Top