Beginner Level Java Interview Questions for Testers
- What is Java?
- Answer: Java is a high-level, object-oriented programming language known for its platform independence.
- Explain the main features of Java.
- Answer: Features include platform independence, object-oriented, simple syntax, robustness, and automatic memory management.
- 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.
- 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.
- 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.
- What is a variable in Java?
- Answer: A variable is a container that holds data values.
- What is the difference between
int
andInteger
in Java?- Answer:
int
is a primitive data type, whileInteger
is a wrapper class forint
.
- Answer:
- Explain the
this
keyword in Java.- Answer:
this
refers to the current instance of the object in which it is used.
- Answer:
- 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.
- Answer:
- How are comments written in Java?
- Answer: Single-line comments start with
//
, and multi-line comments are enclosed between/*
and*/
.
- Answer: Single-line comments start with
- What is the difference between
==
and.equals()
in Java?- Answer:
==
checks for reference equality, while.equals()
checks for content equality for objects.
- Answer:
- What is a constructor in Java?
- Answer: A constructor is a special method used to initialize objects.
- How do you declare a constant in Java?
- Answer: Using the
final
keyword.
- Answer: Using the
- What is the purpose of the
super
keyword?- Answer:
super
is used to call the superclass’s methods, constructors, and access superclass fields.
- Answer:
- What is a Java package?
- Answer: A package is a group of related classes and interfaces.
- Explain the difference between
float
anddouble
in Java.- Answer:
float
is a 32-bit single-precision type, anddouble
is a 64-bit double-precision type.
- Answer:
- What is the
NullPointerException
in Java?- Answer: It occurs when an application attempts to access an object with a
null
reference.
- Answer: It occurs when an application attempts to access an object with a
- How is an
ArrayList
different from an array in Java?- Answer: An
ArrayList
can dynamically resize, while an array has a fixed size.
- Answer: An
- What is the use of the
static
keyword in Java?- Answer: It is used to create class-level variables and methods.
- Explain method overloading in Java.
- Answer: Method overloading allows a class to have multiple methods with the same name but different parameters.
- How do you handle exceptions in Java?
- Answer: By using
try
,catch
,finally
, andthrow
statements.
- Answer: By using
- What is the purpose of the
break
statement in Java?- Answer: It is used to terminate the loop or switch statement.
- What is the default value of the
char
data type in Java?- Answer: The default value is ‘\u0000’ (null character).
- What is the difference between
String
andStringBuilder
?- Answer:
String
is immutable, whileStringBuilder
is mutable.
- Answer:
- How do you convert a string to an integer in Java?
- Answer: Using
Integer.parseInt()
orInteger.valueOf()
.
- Answer: Using
- What is the purpose of the
return
statement in Java?- Answer: It is used to exit a method and return a value.
- Explain the
switch
statement in Java.- Answer:
switch
is a control statement used to select one of many code blocks to be executed.
- Answer:
- 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.
- How do you implement inheritance in Java?
- Answer: By using the
extends
keyword.
- Answer: By using the
- What is the purpose of the
interface
keyword in Java?- Answer: It is used to declare an interface.
- How do you implement polymorphism in Java?
- Answer: By using method overloading and method overriding.
- What is the difference between
while
anddo-while
loops in Java?- Answer:
while
checks the condition before the loop, whiledo-while
checks after the loop.
- Answer:
- What is the purpose of the
throw
keyword in Java?- Answer: It is used to explicitly throw an exception.
- 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).
- 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.
- How is a
for-each
loop different from a regularfor
loop?- Answer:
for-each
is used to iterate over elements of an array or collection, while a regularfor
loop is more general-purpose.
- Answer:
- What is the difference between
public
,private
,protected
, anddefault
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.
- Answer: They control the visibility of classes, methods, and fields.
- What is the
Math.random()
method used for in Java?- Answer: It returns a random number between 0 (inclusive) and 1 (exclusive).
- 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.
- What is the purpose of the
super()
keyword in a constructor?- Answer: It is used to call the constructor of the superclass.
- How do you convert an
int
to aString
in Java?- Answer: By using
String.valueOf()
orInteger.toString()
.
- Answer: By using
- Explain the
&&
and||
operators in Java.- Answer:
&&
is the logical AND operator, and||
is the logical OR operator.
- Answer:
- What is the difference between a
LinkedList
and anArrayList
in Java?- Answer:
ArrayList
uses a dynamic array, whileLinkedList
uses a doubly-linked list.
- Answer:
- How do you declare a constant in an interface in Java?
- Answer: By using the
final
keyword.
- Answer: By using the
- 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.
- Explain the
transient
keyword in Java.- Answer: It is used to indicate that a field should not be serialized.
- What is the purpose of the
break
statement in aswitch
block?- Answer: It is used to terminate the
switch
statement.
- Answer: It is used to terminate the
- How do you implement multiple inheritance in Java?
- Answer: Java does not support multiple inheritance directly; it is achieved using interfaces.
- What is the
Thread.sleep()
method used for in Java?- Answer: It suspends the current thread for a specified amount of time.
- 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
- 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.
- What are checked and unchecked exceptions in Java?
- Answer: Checked exceptions are checked at compile-time, while unchecked exceptions are checked at runtime.
- 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.
- 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.
- Answer:
- Explain the difference between
HashMap
andHashtable
in Java.- Answer: Both are used to store key-value pairs, but
Hashtable
is synchronized, whileHashMap
is not.
- Answer: Both are used to store key-value pairs, but
- 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.
- 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.
- What is the purpose of the
equals()
andhashCode()
methods in Java?- Answer:
equals()
is used to compare the contents of two objects, andhashCode()
returns a hash code value for an object.
- Answer:
- Explain the difference between
poll()
andremove()
methods in theQueue
interface.- Answer: Both methods remove and return the head of the queue, but
poll()
returnsnull
if the queue is empty, whileremove()
throws an exception.
- Answer: Both methods remove and return the head of the queue, but
- What is the
super
keyword used for in a method?- Answer:
super
is used to invoke the superclass method, constructor, or field.
- Answer:
- How does the
this()
constructor call work in Java?- Answer: It is used to invoke the current class constructor.
- 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.
- What is the
Thread
class, and how is it different fromRunnable
in Java?- Answer:
Thread
is a class representing a thread of execution, whileRunnable
is an interface that provides a way to create a thread.
- Answer:
- How do you implement a static block in Java?
- Answer: Using a static block, which is executed when the class is loaded into memory.
- 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.
- Answer:
- What is the
Comparator
interface used for in Java?- Answer:
Comparator
interface is used to define a custom order for objects.
- Answer:
- Describe the
StringBuilder
class in Java.- Answer:
StringBuilder
is a mutable sequence of characters, and it is more efficient thanString
when performing concatenation operations.
- Answer:
- 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.
- Answer:
- How does the
transient
keyword affect object serialization in Java?- Answer: It indicates that a field should not be serialized.
- 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.
- Answer:
- 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.
- 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.
- Explain the difference between
finalize()
anddispose()
methods in Java.- Answer:
finalize()
is a method in theObject
class that is called by the garbage collector before an object is reclaimed, whiledispose()
is a method used to release resources explicitly.
- Answer:
- How do you create a custom exception in Java?
- Answer: By extending the
Exception
class or one of its subclasses.
- Answer: By extending the
- What is the purpose of the
import
statement in Java?- Answer: It is used to include classes from other packages in your program.
- Describe the
Lambda
expression in Java.- Answer: Lambda expressions provide a concise way to express instances of single-method interfaces (functional interfaces).
- How does the
clone()
method work in Java?- Answer: The
clone()
method creates and returns a copy of the object.
- Answer: The
- What is the
super()
constructor call used for?- Answer: It is used to call the constructor of the superclass.
- 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.
- 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.
- Answer:
- 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.
- Answer: The
- What is the purpose of the
assert
statement in Java?- Answer: It is used for debugging purposes and to test assumptions about the program.
- Explain the concept of polymorphism in Java.
- Answer: Polymorphism allows objects of different types to be treated as objects of a common type.
- 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.
- Answer: The
- What is the purpose of the
super
keyword in Java?- Answer:
super
is used to refer to the superclass’s fields, methods, and constructors.
- Answer:
- How do you implement multi-threading in Java?
- Answer: By extending the
Thread
class or implementing theRunnable
interface.
- Answer: By extending the
- 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.
- Answer: The
- 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.
- Answer: An
- 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.
- 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.
- Answer: The
- 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.
- Answer: Shallow copy is achieved using the
- What is the purpose of the
static
keyword in Java?- Answer: It is used to create class-level variables and methods.
- Explain the
Proxy
design pattern in Java.- Answer: The Proxy pattern involves a surrogate or placeholder object controlling access to another object.
- How does the
break
statement work in a loop in Java?- Answer: The
break
statement is used to terminate the loop or switch statement.
- Answer: The
- 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 liketoString()
,equals()
, andhashCode()
.
- Answer: The
- 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.
- What is the purpose of the
IdentityHashMap
class in Java?- Answer:
IdentityHashMap
uses reference equality to compare keys, unlike other map implementations that useequals()
.
- Answer:
- How do you implement a generic class in Java?
- Answer: By using the
<T>
syntax to represent a generic type.
- Answer: By using the
- What is the purpose of the
try
block in exception handling in Java?- Answer: The
try
block contains code that may throw an exception.
- Answer: The
- Explain the
Iterator
interface in Java.- Answer: The
Iterator
interface provides a way to iterate over a collection of objects.
- Answer: The
Advanced Level Java Interview Questions for Testers
- What is the difference between
HashMap
andConcurrentHashMap
in Java?- Answer:
ConcurrentHashMap
allows multiple threads to read and write concurrently, providing better performance in a multi-threaded environment.
- Answer:
- 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
- Answer: A lambda expression is a concise way to represent an anonymous function. Example:
- 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.
- 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.
- 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.
- Answer: The Observer pattern defines a one-to-many dependency between objects. Example: The
- 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.
- Answer: The
- 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.
- Answer:
- 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.
- Answer: Lazy initialization delays the creation of an object until it is actually needed, often achieved using the
- 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.
- Answer:
- 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 likemap
,filter
, andreduce
.
- Answer: The
- What is the purpose of the
ReentrantLock
class in Java, and how does it differ from thesynchronized
keyword?- Answer:
ReentrantLock
provides a more flexible locking mechanism thansynchronized
and allows for more complex synchronization patterns.
- Answer:
- 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.
- Answer:
- 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: Thejava.io
package.
- Answer: The
- 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 asExecutorService
andConcurrentMap
.
- Answer: The
- 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.
- 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.
- Answer: A
- Explain the difference between the
Stack
andHeap
memory areas in Java.- Answer: The
Stack
is used for local variables and method calls, while theHeap
is used for object storage.
- Answer: The
- 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.
- Answer: The
- 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: TheString
pool in Java.
- Answer: The
- 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.
- Answer: A
- 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.
- Answer: The
- 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.
- Answer: The
- 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.
- Answer: The
- 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.
- 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.
- 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.
- Answer:
- 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.
- 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.
- Answer: The
- 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: TheArrayAdapter
in Android.
- Answer: The
- 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.
- 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.
- Answer: The
- 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.
- Answer:
- 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.
- 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.
- Answer: The
- 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.
- Answer: The
- 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.
- Answer:
- 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.
- 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.
- Answer: The
- 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 likeequals()
,hashCode()
, andtoString()
.
- Answer: A
- Explain the concept of
CompletableFutures
in Java and how they differ fromFuture
objects.- Answer:
CompletableFuture
is an extension ofFuture
that provides a more flexible and functional approach to asynchronous programming.
- Answer:
- 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.
- Answer:
- 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.
- Answer: The
- 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()
, andtoString()
that are based solely on their state.
- Answer: Value-based classes are immutable, final, and have implementations of
- 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.
- Answer: The
- 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.
- Answer: The
- 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.
- Answer:
- 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.
- Answer: The
- What is the purpose of the
java.util.concurrent.CopyOnWriteArrayList
class in Java, and how does it differ fromArrayList
in terms of thread safety?- Answer:
CopyOnWriteArrayList
is a thread-safe variant ofArrayList
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.
- Answer:
- 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.
- 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.
- Answer: The
Frequently used Inbuilt Java functions/packages by Java + Selenium Automation testers
Function/Package | Purpose/Description |
---|---|
java.util.Arrays | Provides utility methods for working with arrays, including sorting and searching. |
java.util.Collections | Contains static methods for operating on collections, like sorting and shuffling. |
java.util.regex | Supports regular expressions for pattern matching and string manipulation. |
java.nio.file | Offers file and directory I/O operations, enhancing capabilities for file handling. |
java.time | Provides classes for working with dates, times, and durations in a more modern way. |
java.util.concurrent | Offers utility classes for concurrent programming, including thread pools and locks. |
java.net | Facilitates networking operations, such as creating sockets and working with URLs. |
javax.swing | Enables the creation of graphical user interfaces (GUI) in Java applications. |
junit.framework | Framework for writing and running unit tests in Java. |
TestNG | Testing framework inspired by JUnit, supporting parallel test execution and more. |
Selenium | Web testing framework for automating web browsers. Supports various programming languages. |
RestAssured | Java 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. |
Mockito | Mocking framework for creating and using mock objects for unit testing. |
Log4j | Logging framework for Java applications. Provides flexible and configurable logging. |
Apache POI | Library for reading and writing Microsoft Office files (Excel, Word, PowerPoint). |
Jackson | Library for JSON processing in Java, including data binding and tree model. |
java.util.Properties | Represents a persistent set of properties, often used for configuration settings. |
java.util.concurrent.TimeUnit | Enum representing time units, useful for managing timeouts and delays. |
java.util.stream | Introduces the Stream API for processing sequences of elements in a functional style. |
java.util.Optional | Represents an optional value and helps avoid null pointer exceptions. |
java.util.concurrent.Executor | Interface for objects that execute submitted tasks asynchronously. |
java.util.concurrent.Executors | Factory and utility methods for creating thread pools and executors. |
java.util.concurrent.CountDownLatch | Synchronization aid that allows one or more threads to wait until a set of operations completes. |
java.util.concurrent.CyclicBarrier | Synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. |
java.util.concurrent.Semaphore | Provides a mechanism for controlling access to resources in a multi-threaded environment. |
java.util.concurrent.ConcurrentHashMap | Concurrent, thread-safe implementation of the Map interface. |
java.util.concurrent.LinkedBlockingQueue | A blocking queue that uses linked nodes. Commonly used in producer-consumer scenarios. |
java.util.concurrent.TimeUnit | Enum representing time units, often used with timeouts and delays. |
java.text.SimpleDateFormat | Allows formatting and parsing of dates and times according to a specified pattern. |
java.util.logging | Java Logging API for logging messages from Java programs. |
javax.xml.parsers | Provides classes for parsing XML documents, useful in testing scenarios involving XML data. |
javax.sql | Java Database Connectivity (JDBC) for database-related testing. |
javax.mail | JavaMail API for sending and receiving emails in testing scenarios. |
org.apache.commons.lang3.StringUtils | Provides utility methods for working with strings, often used in testing assertions. |
org.apache.commons.io | Common I/O utilities, including file handling and input/output operations. |
org.apache.http.client | Apache HttpClient for making HTTP requests and testing RESTful APIs. |
org.testng.annotations | TestNG annotations for configuring and customizing test methods and classes. |
org.junit.jupiter.api | JUnit 5 annotations for writing tests with the JUnit testing framework. |
Java Methods Cheatsheet : Most commonly used methods in various testing domains
Domain | Commonly Used Methods |
---|---|
Assertions (JUnit/TestNG) | assertEquals(expected, actual) assertNotEquals(expected, actual) assertTrue(condition) assertFalse(condition) assertNotNull(object) assertNull(object) |
String Manipulation | charAt(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 Framework | List.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 Generation | Random.nextInt() ThreadLocalRandom.current().nextInt() SecureRandom.getInstance("SHA1PRNG").nextInt() |
System Properties and Environment Variables | System.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 Handling | try {...} catch (Exception e) {...} throw new CustomException("message") assertThrows(Exception.class, () -> methodThrowingException()) |
Math Operations | Math.abs(value) Math.max(a, b) <br>- Math.min(a, b) Math.pow(base, exponent) Math.sqrt(value) |
Thread Management | Thread.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 Assertions | assertAll(executables) assertTimeout(duration, executable) assertTimeoutPreemptively(duration, executable) assertThrows(exceptionType, executable) |