JAVA INTERVIEW PREP
A Comprehensive Guide
[Link]
Contents
Basics and Syntax ........................................................................................................... 6
Q1. Explain the JDK, JRE, and JVM. ............................................................................... 6
JVM (Java Virtual Machine) ....................................................................................... 6
JRE (Java Runtime Environment) ............................................................................... 6
JDK (Java Development Kit)....................................................................................... 7
Q2. What are variables in Java? .................................................................................... 7
Types of Variables in Java ......................................................................................... 8
Declaring Variables .................................................................................................. 8
Primitive and Reference Variables ............................................................................ 8
Final Variables ......................................................................................................... 8
Q3. What is typecasting in Java?................................................................................... 9
Types of Typecasting ................................................................................................ 9
Q4: How do you declare an array in Java? ................................................................... 10
Declaring and Initializing an Array ........................................................................... 10
Key Points .............................................................................................................. 11
Q5. Explain the main method in Java.......................................................................... 11
Standard Syntax..................................................................................................... 11
Breakdown of the Signature .................................................................................... 11
Key Points .............................................................................................................. 12
Q6. What is a constructor in Java? .............................................................................. 12
Key Features of Constructors ................................................................................. 13
Types of Constructors ............................................................................................ 13
Q7. Explain method overloading in Java. ..................................................................... 14
How Method Overloading Works............................................................................. 14
Ways to Overload Methods..................................................................................... 14
Advantages of Method Overloading ........................................................................ 15
Key Points .............................................................................................................. 15
Q8. What is a package in Java? ................................................................................... 15
Java Interview Cheat Sheet Page 1 of 57
Key Purposes and Benefits ..................................................................................... 15
Types of Packages .................................................................................................. 16
Syntax and Usage .................................................................................................. 16
Naming Conventions ............................................................................................. 16
Object-Oriented Programming (OOP)............................................................................. 17
Q9. What are the main principles of OOP? .................................................................. 17
Encapsulation ....................................................................................................... 17
Abstraction ............................................................................................................ 17
Inheritance ............................................................................................................ 18
Polymorphism ....................................................................................................... 18
Q10. What is an interface? ......................................................................................... 18
Key Characteristics of Interfaces in Java ................................................................. 18
Why Use Interfaces? .............................................................................................. 19
Q11. Explain the difference between abstract classes and interfaces. ......................... 20
Definition and Purpose ........................................................................................... 20
Implementation and Inheritance ............................................................................ 20
Members and Access Modifiers .............................................................................. 20
Usage Scenarios .................................................................................................... 21
Q12. Explain method overriding. ................................................................................ 21
How It Works ......................................................................................................... 21
Rules of Method Overriding .................................................................................... 22
Q13. What is the super keyword? ............................................................................. 23
Key Points .............................................................................................................. 23
Q14. What are getters and setters in Java? .................................................................. 23
Purpose and Function ............................................................................................ 24
Syntax and Naming Convention .............................................................................. 24
Why Use Getters and Setters? ................................................................................ 25
Q15. What is static in Java? .................................................................................... 25
Key Points .............................................................................................................. 26
Java Interview Cheat Sheet Page 2 of 57
Exception Handling and Assertions................................................................................ 27
Q16. What is exception handling? .............................................................................. 27
Key Concepts ........................................................................................................ 27
Exception Handling Keywords ................................................................................ 27
Basic Syntax .......................................................................................................... 27
Throwing and Declaring Exceptions ........................................................................ 28
Multiple Catch Blocks ............................................................................................ 28
Why Use Exception Handling? ................................................................................ 28
Q17. Explain custom exceptions. ............................................................................... 28
Why Use Custom Exceptions? ................................................................................ 28
How to Create a Custom Exception ........................................................................ 29
Using Custom Exceptions ...................................................................................... 29
Summary............................................................................................................... 29
Q18. What is try-with-resources? ............................................................................... 30
How It Works ......................................................................................................... 30
Key Points .............................................................................................................. 31
Core APIs...................................................................................................................... 32
Q19. What is the String API? ....................................................................................... 32
Key Features of the String API ................................................................................. 32
Common String Methods ....................................................................................... 32
Summary............................................................................................................... 33
Q20. Explain String, StringBuilder, and StringBuffer..................................................... 33
String ................................................................................................................. 33
StringBuilder .................................................................................................. 34
StringBuffer .................................................................................................... 34
Q21. What are wrapper classes? ................................................................................ 35
List of Primitive Types and Their Wrapper Classes ................................................... 35
Why Use Wrapper Classes?.................................................................................... 35
Key Features .......................................................................................................... 36
Java Interview Cheat Sheet Page 3 of 57
Q22. What is the Collections API? .............................................................................. 36
Core Components ................................................................................................. 36
Key Features and Benefits ...................................................................................... 37
Q23. What are generics? ............................................................................................ 38
Why Use Generics? ................................................................................................ 38
How Generics Work ............................................................................................... 38
Generic Classes and Interfaces .............................................................................. 39
Wildcards .............................................................................................................. 39
Type Erasure .......................................................................................................... 39
Q24. What is the Iterator interface?....................................................................... 39
Key Features .......................................................................................................... 39
Main Methods ........................................................................................................ 40
Benefits ................................................................................................................. 41
Q25. Explain the difference between Iterator and ListIterator. ........................ 41
Summary of Key Differences .................................................................................. 42
Q26. What is a Map? .................................................................................................. 42
Key Characteristics ................................................................................................ 43
Core Methods ........................................................................................................ 43
Collection Views .................................................................................................... 43
Common Implementations .................................................................................... 43
Use Cases ............................................................................................................. 44
Concurrency ................................................................................................................. 45
Q27. What is concurrency? ........................................................................................ 45
Key Concepts ........................................................................................................ 45
Benefits of Concurrency ......................................................................................... 45
Java Concurrency Tools and APIs ............................................................................ 45
Synchronization and Safety .................................................................................... 46
Q28. What is a thread? .............................................................................................. 46
Key Points .............................................................................................................. 46
Java Interview Cheat Sheet Page 4 of 57
Q29. What is the difference between a process and a thread? ..................................... 47
Process ................................................................................................................. 47
Thread ................................................................................................................... 47
Q30. What is multithreading? ..................................................................................... 48
Key Features of Multithreading in Java ..................................................................... 48
Advantages............................................................................................................ 49
Disadvantages ....................................................................................................... 49
Example Use Cases ............................................................................................... 50
Q31. What is the synchronized keyword? ............................................................... 50
How It Works ......................................................................................................... 50
Key Points .............................................................................................................. 50
Q32. What is deadlock? ............................................................................................. 51
How Deadlock Occurs ........................................................................................... 51
Characteristics of Deadlock ................................................................................... 52
Prevention Strategies ............................................................................................. 52
Q33. What are the states of a thread? ......................................................................... 53
Q34. What is the volatile keyword? ....................................................................... 54
Key Properties of volatile................................................................................... 54
Stream API.................................................................................................................... 55
Q35. What is the Stream API in Java? .......................................................................... 55
Key Characteristics ................................................................................................ 55
Common Stream Operations .................................................................................. 55
Stream Sources ..................................................................................................... 56
Q36. What is the difference between map and flatMap in Streams? .......................... 56
map ....................................................................................................................... 56
flatMap ............................................................................................................... 57
Java Interview Cheat Sheet Page 5 of 57
Basics and Syntax
Q1. Explain the JDK, JRE, and JVM.
JDK (Java Development Kit), JRE (Java Runtime Environment), and JVM (Java Virtual
Machine) are three core components of the Java platform, each serving a distinct purpose
in the development and execution of Java applications.
JVM (Java Virtual Machine)
• The JVM is an abstract machine that enables computers to run Java programs by
converting Java bytecode (compiled Java source code) into machine-specific code
that the computer's hardware can execute.
• It is the core component responsible for loading, verifying, and executing Java
bytecode, handling memory management, security, and other runtime tasks.
• The JVM is platform-dependent—different operating systems require different JVM
implementations—but the bytecode it executes is platform-independent, which
allows Java to be "write once, run anywhere."
• The JVM can also run bytecode compiled from other languages that target the JVM,
not just Java.
JRE (Java Runtime Environment)
• The JRE is a software package that provides the environment required to run Java
applications.
• It includes the JVM, Java class libraries, and other supporting files necessary for
execution, but does not include development tools like compilers or debuggers.
• If you only need to run Java programs (not develop them), installing the JRE is
sufficient.
• The JRE is platform-dependent, with different installers for different operating
systems.
Java Interview Cheat Sheet Page 6 of 57
JDK (Java Development Kit)
• The JDK is a full-featured software development kit for Java developers.
• It includes everything found in the JRE (i.e., JVM and libraries), plus development
tools such as the Java compiler, debugger, and other utilities required to write,
compile, and debug Java programs.
• The JDK is also platform-dependent, and you need the appropriate version for your
operating system.
• If you want to develop Java applications, you need the JDK.
Comparison Table
Component Purpose Includes Platform Use Case Development
Dependent Tools
JDK Java JRE + Yes Developing Yes
development compiler, Java
(write, debugger applications
compile,
debug)
JRE Running Java JVM + Yes Running Java No
applications libraries applications
JVM Executes Java - Yes Bytecode No
bytecode execution
Q2. What are variables in Java?
Variables in Java are named containers used to store data values that can be manipulated
during the execution of a program. Each variable has a specific data type that determines
the kind of data it can hold, such as integers, floating-point numbers, characters, text, or
boolean values.
Java Interview Cheat Sheet Page 7 of 57
Types of Variables in Java
Java variables are categorized into three main types:
• Local Variables: Declared inside a method, constructor, or block. They are only
accessible within that scope and must be initialized before use, as they do not have
default values.
• Instance Variables: Declared inside a class but outside any method, constructor,
or block. Each object (instance) of the class has its own copy of these variables.
They are initialized to default values if not explicitly assigned.
• Static (Class) Variables: Declared with the static keyword inside a class but
outside any method. These variables are shared among all instances of the class
and are also initialized to default values if not explicitly assigned.
Declaring Variables
To declare a variable in Java, specify the data type followed by the variable name.
Optionally, you can assign a value at the time of declaration. For example:
Primitive and Reference Variables
• Primitive variables store basic data types (e.g., int, double, boolean).
• Reference variables store references to objects, such as instances of classes like
String.
Final Variables
If you want a variable's value to remain constant and not be changed, use the final
keyword:
Java Interview Cheat Sheet Page 8 of 57
Summary Table
Type Where Declared Scope/Lifetime Default Value
Local Inside methods/blocks Only within that None (must
method/block assign)
Instance Inside class, outside For each object, as long as 0, null, false
methods object lives
Static Inside class, with Shared among all objects of 0, null, false
(Class) static the class
Q3. What is typecasting in Java?
Typecasting in Java is the process of converting a variable from one data type to another.
This is often necessary when you want to perform operations involving different data types
or when you need to store a value in a variable of a different type.
Types of Typecasting
There are two main types of typecasting in Java:
• Widening Type Casting (Implicit Typecasting)
o Converts a smaller (lower) data type to a larger (higher) data type.
o Performed automatically by the compiler.
o Safe, as there is no risk of data loss.
o Example: int to double, byte to int.
o Example code:
The value of num (50) is automatically converted to a double (50.0).
Java Interview Cheat Sheet Page 9 of 57
• Narrowing Type Casting (Explicit Typecasting)
o Converts a larger (higher) data type to a smaller (lower) data type.
o Must be done manually by the programmer using a cast operator.
o May result in data loss or precision loss.
o Example: double to int, int to byte.
o Example code:
The value of myDouble (9.78) is converted to an integer (9), truncating the decimal part.
Q4: How do you declare an array in Java?
To declare an array in Java, you specify the data type of the elements, followed by square
brackets, and then the array name. The general syntax is:
dataType[] arrayName;
• dataType can be any valid Java type (e.g., int, double, String).
• arrayName is the identifier for the array variable.
Declaring and Initializing an Array
You can both declare and initialize an array in a single statement in a few ways:
With Explicit Values
This creates an array and fills it with the specified values.
Java Interview Cheat Sheet Page 10 of 57
With a Fixed Size
If you want to specify the size but not the values (the array will contain default values):
This allocates memory for the array, but you can assign values later.
Key Points
• Arrays in Java are zero-indexed: the first element is at index 0.
• Array size is fixed once declared.
• You can access or modify elements using their index.
• Arrays can be of primitive types or reference types (objects).
Q5. Explain the main method in Java.
The main method is the entry point for every standalone Java application. When you run a
Java program, the Java Virtual Machine (JVM) looks for this method to begin execution.
Without a correctly defined main method, the JVM cannot start your program.
Standard Syntax
Breakdown of the Signature
• public: The method must be accessible from anywhere, allowing the JVM to invoke
it from outside the class.
• static: The JVM can call the method without creating an instance of the class. This
is essential because no objects exist when execution starts.
• void: The method does not return any value to the JVM when it finishes.
Java Interview Cheat Sheet Page 11 of 57
• main: The method name must be exactly main, as this is what the JVM expects as
the entry point.
• String[] args: This parameter is an array of strings that stores command-line
arguments passed to the program.
Usage Example
When you run this program, the JVM calls the main method, and "Hello, World!" is printed
to the console.
Key Points
• The main method is required for standalone Java applications.
• The signature must be exactly public static void main(String[] args).
• The main method can call other methods and serve as the starting point for
program logic.
• If the main method is missing or incorrectly defined, the JVM will produce an error
and not run the program.
Q6. What is a constructor in Java?
A constructor in Java is a special method used to initialize objects when they are created. It
is automatically called every time an object is instantiated using the new keyword. The
primary purpose of a constructor is to set up the initial state of the object by assigning
values to its fields or performing any necessary setup steps.
Java Interview Cheat Sheet Page 12 of 57
Key Features of Constructors
• Same Name as Class: The constructor must have the same name as the class in
which it is defined.
• No Return Type: Constructors do not have a return type—not even void.
• Automatic Invocation: The constructor is invoked automatically when an object is
created; you do not call it explicitly.
• Initialization: Constructors are used to initialize the object's attributes and ensure it
is in a valid state from the beginning.
Types of Constructors
• Default Constructor: Provided by Java if no constructor is explicitly defined. It
initializes the object with default values (e.g., 0, null).
• No-Argument Constructor: Explicitly defined by the programmer and takes no
parameters. It can include custom initialization code.
• Parameterized Constructor: Takes arguments to initialize the object with specific
values, allowing for flexible and controlled initialization.
• Copy Constructor: Used to create a new object as a copy of an existing object. Java
does not provide this by default; it must be implemented manually.
Example
In this example, the Car constructor initializes the model and year attributes when a new
Car object is created.
Java Interview Cheat Sheet Page 13 of 57
Q7. Explain method overloading in Java.
Method overloading in Java is a feature that allows a class to have multiple methods with
the same name, as long as their parameter lists differ in number, type, or order of
parameters. This enables you to define several versions of a method to handle different
types or numbers of inputs, improving code readability and reducing redundancy.
How Method Overloading Works
• Same Method Name: All overloaded methods share the same name.
• Different Parameters: Methods must differ in the number of parameters, the type
of parameters, or the sequence of parameter types.
• Return Type Irrelevant: Changing only the return type does not constitute
overloading; the parameter list must be different.
Ways to Overload Methods
• By Number of Parameters:
• By Type of Parameters:
• By Sequence of Parameters:
Java Interview Cheat Sheet Page 14 of 57
Advantages of Method Overloading
• Improves code readability by grouping similar operations under a single method
name5.
• Reduces code redundancy since you don't need to create uniquely named
methods for similar actions5.
• Enables compile-time polymorphism (static polymorphism), where the method to
be executed is determined at compile time based on the arguments.
Key Points
• Overloading can be applied to static methods, instance methods, and even
constructors.
• The main method can also be overloaded, though only the standard signature is
used as the application's entry point.
• Overloading is not possible by changing only the return type or by varying access
modifiers.
Q8. What is a package in Java?
A package in Java is a namespace that organizes a group of related classes, interfaces,
enumerations, and sub-packages, much like a folder in a file directory. Packages help
developers manage and structure their code by grouping similar types together, making
code easier to maintain and locate.
Key Purposes and Benefits
• Organization: Packages group related classes, making large projects easier to
manage and understand.
• Avoid Naming Conflicts: By encapsulating classes within packages, Java allows
different packages to have classes with the same name without conflict.
• Access Control: Packages provide a way to control access to classes and
members. Classes with default or protected access are only accessible within the
same package.
Java Interview Cheat Sheet Page 15 of 57
• Namespace Management: Packages act as namespaces, preventing type name
clashes and making it easier to find relevant types in a library.
• Reusability: Code in packages can be reused across different projects or modules.
Types of Packages
• Built-in Packages: Provided by the Java API, such as [Link], [Link], and
[Link], containing commonly used classes and interfaces.
• User-defined Packages: Created by developers to organize their own classes and
interfaces.
Syntax and Usage
To declare a package, use the package keyword at the top of your Java source file.
To use classes from a package, use the import statement:
Naming Conventions
• Package names are written in all lowercase.
• Often use reversed domain names (e.g., [Link]) to ensure
uniqueness and avoid conflicts.
Java Interview Cheat Sheet Page 16 of 57
Object-Oriented Programming (OOP)
Q9. What are the main principles of OOP?
The four main principles of OOP are:
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
Encapsulation
Encapsulation is the practice of bundling data (fields) and the methods (functions) that
operate on that data into a single unit, typically a class. It also involves restricting direct
access to some of an object's components, which is usually done through access
modifiers (like private, protected, and public). This protects the internal state of an
object and only exposes a controlled interface for interaction.
Benefits:
• Hides internal implementation details
• Promotes modularity and code reuse
• Makes code easier to maintain and debug
Abstraction
Abstraction means representing complex real-world problems in simplified models by
focusing on essential features and hiding unnecessary details. In OOP, abstraction is
achieved through abstract classes and interfaces, allowing programmers to define what an
object does without specifying how it does it.
Benefits:
• Reduces complexity
• Increases code clarity and usability
• Allows focusing on high-level operations
Java Interview Cheat Sheet Page 17 of 57
Inheritance
Inheritance allows a new class (subclass or child) to acquire the properties and behaviors
(fields and methods) of an existing class (superclass or parent). This enables code reuse
and establishes a relationship between different classes in a hierarchy.
Benefits:
• Promotes code reuse
• Supports hierarchical classification
• Enables the creation of more complex types from simpler ones
Polymorphism
Polymorphism enables objects to be treated as instances of their parent class rather than
their actual class. The most common use is method overriding, where a subclass provides
a specific implementation of a method that is already defined in its superclass. This allows
one interface to be used for a general class of actions.
Benefits:
• Increases code flexibility and extensibility
• Allows for dynamic method invocation
• Supports the design of generic interfaces and reusable code
Q10. What is an interface?
An interface in Java is a reference type that defines a set of abstract method signatures
(without implementations) that any implementing class must provide. It acts as a contract
or a template, specifying what methods a class should have, but not how those methods
should be implemented. This allows different classes to implement the same set of
behaviors in their own way, promoting flexibility and code reusability.
Key Characteristics of Interfaces in Java
• Method Signatures Only: Interfaces can declare methods, but these methods do
not have bodies; the implementing class must provide the method
implementations.
Java Interview Cheat Sheet Page 18 of 57
• No Constructors or State: Interfaces cannot have constructors and cannot be
instantiated directly. They also cannot contain instance variables—only constants
(which are implicitly public, static, and final).
• Implementation: A class implements an interface using the implements keyword
and must provide concrete implementations for all of the interface’s methods.
• Multiple Inheritance: Java does not support multiple inheritance with classes, but
a class can implement multiple interfaces, allowing it to inherit behaviors from
several sources.
• Abstraction: Interfaces are used to achieve total abstraction, hiding the
implementation details and exposing only the required behaviors.
Example
Why Use Interfaces?
• Abstraction: Interfaces let you define what operations can be performed, not how
they are performed.
• Polymorphism: Code can interact with objects through their interface type,
allowing different implementations to be used interchangeably.
Java Interview Cheat Sheet Page 19 of 57
• Loose Coupling: Interfaces decouple code from specific implementations, making
systems more flexible and easier to maintain.
• Multiple Inheritance: They allow a class to inherit behaviors from multiple sources.
Q11. Explain the difference between abstract classes and interfaces.
Definition and Purpose
• Abstract Classes are used to define a common base for a group of related classes,
allowing you to provide both shared (implemented) functionality and abstract
(unimplemented) methods that must be overridden by subclasses. They establish
an "is-a" relationship, meaning subclasses are specialized types of the abstract
class.
• Interfaces define a contract that unrelated classes can agree to implement,
specifying only method signatures (and sometimes properties), but no concrete
implementation (except for default methods). Interfaces promote a "can-do"
relationship, focusing on what a class can do, not what it is.
Implementation and Inheritance
• Abstract classes can contain both abstract methods (no implementation) and
concrete methods (with implementation).
• Interfaces traditionally contain only method signatures (no implementation), though
Java (since Java 8) allows default and static methods in interfaces.
• A class can inherit from only one abstract class (single inheritance), but it can
implement multiple interfaces (multiple inheritance of type).
Members and Access Modifiers
• Abstract classes can have fields (variables), properties, constructors, and methods
with various access modifiers (private, protected, public).
• Interfaces cannot have fields (only constants), cannot have constructors, and all
members are public by default.
Java Interview Cheat Sheet Page 20 of 57
Usage Scenarios
• Use an abstract class when:
• You want to share code among several closely related classes.
• You need to provide common implemented functionality and enforce certain
methods to be overridden.
• You want to define non-public members or constructors.
• Use an interface when:
• You want to define a contract for unrelated classes to implement36.
• You need to provide multiple behaviors to a class (since multiple interfaces
can be implemented).
• You require only method signatures without shared implementation.
Q12. Explain method overriding.
Method overriding in Java occurs when a subclass provides its own implementation for a
method that is already defined in its superclass. This allows the subclass to tailor or extend
the behavior inherited from the parent class.
How It Works
• Both the superclass and the subclass must have a method with the same name,
return type (or a subtype, known as covariant return type), and parameter list.
• When a method is called on an object, the version in the subclass is executed if the
object is an instance of the subclass, even if the reference type is of the superclass.
This is known as runtime polymorphism or dynamic method dispatch.
Java Interview Cheat Sheet Page 21 of 57
Example
If you run:
Here, [Link]() calls the method in Dog, not Animal, because the actual object is a Dog.
Rules of Method Overriding
• The method in the subclass must have the same name, return type, and parameter
list as in the superclass.
• The overriding method cannot have a more restrictive access modifier than the
overridden method (e.g., you can't override a public method with a protected
one).
• You cannot override methods that are final, static, or private.
• The overriding method can throw fewer or more specific checked exceptions than
the overridden method.
Java Interview Cheat Sheet Page 22 of 57
• Use the @Override annotation to indicate that a method is intended to override a
superclass method; this helps catch errors at compile time.
Q13. What is the super keyword?
The super keyword in Java is used within a subclass to refer to its immediate superclass
(parent class). It serves three main purposes:
• Calling Superclass Methods:
If a subclass overrides a method from its superclass but still needs to execute the
superclass's version, it can do so using [Link](). This is useful for
extending or modifying inherited behavior rather than completely replacing it.
• Accessing Superclass Fields:
When a subclass defines a field with the same name as one in its superclass,
[Link] allows the subclass to access the superclass's version,
resolving naming conflicts.
• Invoking Superclass Constructors:
Inside a subclass constructor, super() or super(arguments) can be used as
the first statement to explicitly call a constructor from the superclass. This is
essential for proper initialization, especially when the superclass does not have a
no-argument constructor or when specific setup is needed.
Key Points
• super() must be the first statement in a subclass constructor if used.
• super cannot be used in static contexts.
• It helps resolve ambiguity and ensures correct initialization and method/field
access in inheritance hierarchies.
Q14. What are getters and setters in Java?
Getters and setters are special methods used in Java to access and modify the values of
private variables in a class. They are fundamental to the concept of encapsulation,
which is the practice of hiding an object's internal state and requiring all interaction to be
performed through an object's methods.
Java Interview Cheat Sheet Page 23 of 57
Purpose and Function
• Getters (also known as accessors) retrieve or "get" the value of a private variable.
• Setters (also known as mutators) update or "set" the value of a private variable.
By declaring variables as private, you prevent direct access from outside the class.
Getters and setters provide controlled access, allowing you to add validation, formatting,
or other logic when getting or setting a value.
Syntax and Naming Convention
• A getter method typically starts with get, followed by the variable name with the
first letter capitalized.
• A setter method starts with set, followed by the variable name with the first letter
capitalized.
Example
Java Interview Cheat Sheet Page 24 of 57
Why Use Getters and Setters?
• Encapsulation & Data Hiding: Prevents direct access to sensitive data, enforcing
security and integrity.
• Validation: Setters can include checks to ensure only valid data is accepted (e.g.,
restricting a number to a certain range).
• Read-Only/Write-Only: You can provide only a getter (read-only) or only a setter
(write-only), controlling how variables are accessed.
• Flexibility: The internal implementation can change without affecting code that
uses the class, as long as the getter/setter interface remains the same.
Q15. What is static in Java?
The static keyword in Java is a non-access modifier used to indicate that a particular
member (variable, method, block, or nested class) belongs to the class itself, rather than to
instances of the class. This means:
• Static Variables:
Also known as class variables, these are shared among all instances of the class.
Only one copy exists, regardless of how many objects are created. Changing the
value affects all instances.
• Static Methods:
These can be called without creating an object of the class. They can only access
other static members (variables or methods) and cannot use this or super
keywords, as they are not associated with any specific instance.
• Static Blocks:
Used for static initialization of a class. The code inside a static block runs once
when the class is loaded into memory.
• Static Nested Classes:
A nested class declared as static does not have access to instance members of
the outer class and can be instantiated without an instance of the outer class.
Java Interview Cheat Sheet Page 25 of 57
Key Points
• Static members are accessed using the class name, not via objects (e.g.,
[Link]();).
• They are initialized when the class is loaded and exist independently of any object.
• The main method in Java is static so it can be called by the Java runtime without
instantiating the class.
Java Interview Cheat Sheet Page 26 of 57
Exception Handling and Assertions
Q16. What is exception handling?
Exception handling in Java is a mechanism that allows developers to manage errors and
other exceptional events that occur during the execution of a program. Instead of letting
the program crash, Java provides structured ways to detect, catch, and handle these errors
gracefully, improving program reliability and user experience.
Key Concepts
• Exception: An event that disrupts the normal flow of the program, such as invalid
input, file not found, or division by zero. When such an event occurs, Java "throws"
an exception.
• Types of Exceptions:
o Checked exceptions (must be handled or declared, e.g., IOException)
o Unchecked exceptions (runtime exceptions, e.g.,
NullPointerException)
o Errors (serious problems, e.g., OutOfMemoryError)
Exception Handling Keywords
• try: Contains code that might throw an exception.
• catch: Handles the exception if one occurs in the associated try block.
• finally: (Optional) Executes code after try and catch, regardless of whether an
exception was thrown.
Basic Syntax
Java Interview Cheat Sheet Page 27 of 57
Throwing and Declaring Exceptions
• throw: Used to explicitly throw an exception, often in custom validation logic.
• throws: Used in method signatures to declare that the method may throw certain
exceptions, passing responsibility to the caller.
Multiple Catch Blocks
You can have multiple catch blocks to handle different types of exceptions separately.
Since Java 7, a single catch block can handle multiple exception types using the pipe (|)
symbol.
Why Use Exception Handling?
• Prevents abrupt program termination.
• Allows graceful recovery from errors.
• Separates error-handling code from regular code, improving readability and
maintainability.
Q17. Explain custom exceptions.
Custom exceptions in Java are user-defined exception classes that extend either the
Exception class (for checked exceptions) or the RuntimeException class (for
unchecked exceptions). They are used when the standard Java exceptions do not
adequately describe a specific error situation in your application, allowing for more
meaningful and precise error handling.
Why Use Custom Exceptions?
• To categorize and handle application-specific error conditions with descriptive
names.
• To provide more context or additional information about an error.
• To improve code readability and maintainability by making error handling more
explicit and meaningful.
Java Interview Cheat Sheet Page 28 of 57
How to Create a Custom Exception
For Checked Exceptions
Extend the Exception class:
You can also provide a constructor that accepts a Throwable cause, preserving the root
cause of the exception:
Checked exceptions must be declared in the method signature using throws and handled
with try-catch blocks.
For Unchecked Exceptions
Extend the RuntimeException class:
Unchecked exceptions do not need to be declared or caught explicitly.
Using Custom Exceptions
Throw your custom exception in code where a specific error condition occurs. Custom
exceptions can include extra fields and methods to provide more context. This allows you
to pass and retrieve additional information about the error.
Summary
Custom exceptions in Java are created by extending Exception or RuntimeException,
allowing developers to handle application-specific errors more precisely and informatively.
They can include custom messages, root causes, and additional context, making error
handling clearer and more robust.
Java Interview Cheat Sheet Page 29 of 57
Q18. What is try-with-resources?
The try-with-resources statement in Java is a special form of the try statement that
simplifies the management of resources such as files, streams, sockets, or database
connections—any object that must be closed after use. Introduced in Java 7, it ensures
that each resource is automatically closed at the end of the statement, even if an exception
occurs, reducing boilerplate code and the risk of resource leaks.
How It Works
• Resource Declaration:
Resources are declared within parentheses after the try keyword. Each resource
must implement the AutoCloseable interface (which includes all classes that
implement Closeable).
• Automatic Closing:
When the try block finishes (either normally or due to an exception), all declared
resources are automatically closed in reverse order of their declaration—no need
for an explicit finally block.
• Exception Handling:
You can still use catch and finally blocks as needed for additional exception
handling or cleanup.
Example
Java Interview Cheat Sheet Page 30 of 57
You can also declare multiple resources:
Key Points
• Reduces Boilerplate: No need for explicit finally blocks to close resources.
• Prevents Resource Leaks: Ensures all resources are closed, even if exceptions
occur.
• Multiple Resources: Supports declaring and managing multiple resources in a
single statement, closed in reverse order.
• Requirement: Resources must implement the AutoCloseable interface.
Java Interview Cheat Sheet Page 31 of 57
Core APIs
Q19. What is the String API?
The String API refers to the String class and its comprehensive set of methods for
creating, manipulating, and analyzing character strings. In Java, all string literals (like
"hello") are instances of the String class.
Key Features of the String API
• Immutability:
Strings in Java are immutable, meaning once created, their values cannot be
changed. Any operation that seems to modify a string actually creates a new
String object.
• Creation:
Strings can be created using string literals, the new keyword, or from character
arrays.
• Common Constructors:
o String()
o String(String original)
o String(char[] value)
o String(char[] value, int offset, int count)5
Common String Methods
The String API provides numerous built-in methods for various operations:
Method Description
length() Returns the length of the string
charAt(int) Returns the character at a specified index
substring() Returns a substring
concat() Concatenates two strings
equals() Compares two strings for equality
equalsIgnoreCase() Compares two strings, ignoring case
Java Interview Cheat Sheet Page 32 of 57
Method Description
compareTo() Lexicographically compares two strings
contains() Checks if a string contains a specified sequence
replace() Replaces characters or substrings
split() Splits the string into an array based on a delimiter
toLowerCase() Converts to lower case
toUpperCase() Converts to upper case
trim() Removes whitespace from both ends
startsWith() Checks if the string starts with a specified prefix
endsWith() Checks if the string ends with a specified suffix
indexOf() Finds the first occurrence of a character or substring
lastIndexOf() Finds the last occurrence of a character or substring
matches() Checks if the string matches a regular expression
Summary
The String API in Java is a powerful set of tools for handling text, supporting everything from
basic creation and comparison to advanced manipulation, searching, formatting, and
regular expressions.
Q20. Explain String, StringBuilder, and StringBuffer.
Java provides three main classes for handling and manipulating sequences of characters:
String, StringBuilder, and StringBuffer. Each serves a different purpose and has
distinct characteristics regarding mutability, thread safety, and performance.
String
• Immutability: Strings are immutable, meaning once a String object is created, its
value cannot be changed. Any operation that appears to modify a string actually
creates a new String object.
Java Interview Cheat Sheet Page 33 of 57
• Thread Safety: Because they are immutable, Strings are inherently thread-safe.
• Performance: Modifying strings frequently (e.g., concatenation in loops) can lead to
performance issues due to the creation of many intermediate objects.
• Use Case: Suitable when the string content will not change, or for use as keys in
collections, constants, etc.
StringBuilder
• Mutability: StringBuilder is mutable; its contents can be modified without
creating new objects.
• Thread Safety: Not thread-safe—its methods are not synchronized. This makes it
unsuitable for use in multi-threaded environments where the same instance is
accessed by multiple threads.
• Performance: Faster than StringBuffer due to the lack of synchronization
overhead, making it the preferred choice for string manipulation in single-threaded
contexts.
• Use Case: Ideal for frequent string modifications in single-threaded environments,
such as building strings in loops.
StringBuffer
• Mutability: StringBuffer is mutable, allowing modifications to its content
without creating new objects.
• Thread Safety: Thread-safe—its methods are synchronized, making it safe for use in
multi-threaded environments where instances may be accessed by multiple
threads simultaneously.
• Performance: Slower than StringBuilder due to synchronization overhead, but
still more efficient than String for frequent modifications.
• Use Case: Best for scenarios requiring frequent string modifications in multi-
threaded environments.
Java Interview Cheat Sheet Page 34 of 57
Q21. What are wrapper classes?
Wrapper classes in Java are special classes that encapsulate (or "wrap") primitive data
types (such as int, char, boolean, etc.) into objects. This allows primitive values to be
treated as objects, enabling their use in situations where only objects are allowed, such as
with Java Collections and generics.
List of Primitive Types and Their Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Why Use Wrapper Classes?
• Collections and Generics: Java's collections (like ArrayList, HashMap) and
generics only work with objects, not primitives. Wrapper classes allow primitives to
be stored in collections (e.g., List<Integer>, not List<int>).
• Utility Methods: Wrapper classes provide useful methods for converting between
types, parsing strings to numbers, comparing values, and more (e.g.,
[Link](), [Link]()).
• Constants: Wrapper classes define constants such as Integer.MAX_VALUE and
Double.MIN_VALUE that are useful in programming1.
• Interoperability: Some Java APIs require objects, so wrapper classes allow
primitive values to be passed where objects are needed.
• Autoboxing and Unboxing: Java automatically converts between primitives and
their wrapper classes as needed (autoboxing: primitive to object, unboxing: object
to primitive).
Java Interview Cheat Sheet Page 35 of 57
Example
Key Features
• Immutability: Wrapper class objects are immutable, just like Strings.
• Type Conversion: They provide methods to convert between strings and numeric
types, and vice versa (e.g., [Link]("123"))1.
• Custom Wrapper Classes: Developers can create their own wrapper classes to
add extra functionality or behavior to primitive types.
Q22. What is the Collections API?
The Collections API in Java, more formally known as the Java Collections Framework, is a
unified architecture for representing, storing, and manipulating groups of objects, known
as collections. It provides a standard way to handle data structures such as lists, sets,
queues, and maps, making it easier to manage groups of objects in a consistent and
efficient manner.
Core Components
Interfaces
• The framework is built around a set of core interfaces, each defining a different type
of collection:
o Collection (the root interface)
o List (ordered collections, e.g., ArrayList, LinkedList)
o Set (collections with no duplicate elements, e.g., HashSet, TreeSet)
Java Interview Cheat Sheet Page 36 of 57
o Queue (collections designed for holding elements prior to processing, e.g.,
PriorityQueue)
o Map (object that maps keys to values, e.g., HashMap, TreeMap)—note that
Map does not extend Collection.
Implementations
• The framework provides concrete classes that implement these interfaces, such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap56.
Algorithms
• The API includes reusable algorithms for sorting, searching, shuffling, reversing, and
more, usually provided as static methods in the Collections utility class.
Utilities
• The Collections class offers static methods for common operations (e.g.,
sorting, searching, synchronization, making collections unmodifiable).
Key Features and Benefits
• Interoperability: Collections can interact seamlessly, regardless of their underlying
implementation.
• Reusability: Reduces the need to design new data structures from scratch,
promoting code reuse.
• Performance: Provides efficient, high-performance implementations for common
data structures.
• Type Safety: With generics, collections can be type-safe, reducing runtime errors.
• Thread Safety and Immutability: Provides wrappers for thread-safe and immutable
collections.
• Fail-Fast Iterators: Iterators quickly detect concurrent modification and fail cleanly.
Java Interview Cheat Sheet Page 37 of 57
Summary Table
Interface Description Example Implementations
List Ordered, allows duplicates ArrayList, LinkedList
Set Unordered, no duplicates HashSet, TreeSet
Queue FIFO structure, processing elements PriorityQueue, LinkedList
Map Key-value pairs, unique keys HashMap, TreeMap
Q23. What are generics?
Generics in Java are a language feature introduced in Java 5 that enable classes,
interfaces, and methods to operate on objects of various types while providing compile-
time type safety. This means you can write a single class or method that works with
different types, reducing code duplication and catching type-related errors at compile
time, rather than at runtime.
Why Use Generics?
• Type Safety: Generics ensure that you can only use the intended type with a
collection or class, preventing ClassCastException at runtime.
• Code Reusability: You can write flexible and reusable code that works with any
object type.
• Elimination of Explicit Casting: With generics, you do not need to cast objects
when retrieving them from a collection.
How Generics Work
Generics use type parameters (like <T>, <E>, <K, V>) to specify the type of objects a
class, interface, or method can work with. For example, List<String> ensures only
String objects can be added, and retrieved elements are automatically treated as
String.
Java Interview Cheat Sheet Page 38 of 57
Generic Classes and Interfaces
A generic class or interface declares one or more type parameters:
You can create instances with different types:
This same technique applies to interfaces.
Wildcards
Generics support wildcards, such as <?> (unbounded wildcard), which means any type, or
<? extends Number>, which means any type that is a subclass of Number.
Type Erasure
At runtime, generic type information is erased (type erasure), so all generic types are
implemented as Object and type checks are enforced only at compile time. This means
you cannot use primitive types directly as type parameters (use boxed types like Integer
instead).
Q24. What is the Iterator interface?
The Iterator interface in Java is a core part of the Java Collections Framework that
provides a standard way to traverse or iterate over the elements of a collection (such as
ArrayList, HashSet, etc.). It is designed to allow sequential access to elements,
regardless of the collection’s underlying structure.
Key Features
• Traversal:
Iterator allows you to loop through a collection, accessing each element in turn
without exposing the collection’s internal structure.
Java Interview Cheat Sheet Page 39 of 57
• Element Removal:
The remove() method enables you to safely remove elements from the underlying
collection during iteration, which is not possible with a standard for-each loop.
• Uniform Interface:
All collections in Java that implement the Collection interface provide an
iterator() method, which returns an Iterator for that collection.
Main Methods
Method Description
boolean hasNext() Returns true if there are more
elements to iterate over1456.
E next() Returns the next element in the
iteration.
void remove() Removes the last element
returned by next() (optional).
void forEachRemaining(Consumer<? Performs an action for each
super E> action) remaining element (Java 8+).
Example
Java Interview Cheat Sheet Page 40 of 57
This code prints each fruit in the list using an Iterator.
Benefits
• Safe Modification:
You can remove elements during iteration without causing errors or unexpected
behavior, which can happen if you modify a collection directly while looping.
• Decoupling:
The Iterator pattern decouples the collection’s implementation from the code that
uses it, making your code more flexible and reusable.
• Standardization:
Provides a consistent way to traverse different types of collections.
Q25. Explain the difference between Iterator and ListIterator.
Feature Iterator ListIterator
Applicable Can be used with any Only works with List implementations (e.g.,
Collections Collection (List, ArrayList, LinkedList)
Set, etc.)
Direction of Forward only Bidirectional (forward and backward)
Traversal
Index Access Cannot obtain element Can get next and previous element indices
indices using nextIndex() and
previousIndex()
Element Cannot add elements Can add elements at the current position
Addition during iteration during iteration using add()
Element Can remove elements Can remove, replace (set()), and add
Modification with remove() elements
Methods hasNext(), next(), All Iterator methods plus: hasPrevious(),
remove() previous(), add(), set(),
nextIndex(), previousIndex()
Java Interview Cheat Sheet Page 41 of 57
Feature Iterator ListIterator
Use Case General traversal of any Advanced list manipulation where
collection bidirectional traversal, index access, or in-
place modifications are needed
Summary of Key Differences
• Scope:
o Iterator is universal and can traverse any collection (List, Set, Map,
etc.).
o ListIterator is specific to lists and cannot be used with other collection
types.
• Traversal:
o Iterator traverses in one direction (forward).
o ListIterator traverses in both directions (forward and backward).
• Functionality:
o Iterator allows element removal during iteration.
o ListIterator allows element removal, addition, and replacement during
iteration, and provides index information.
• When to Use:
Use Iterator for simple, forward-only traversal of any collection.
Use ListIterator when you need to traverse a list in both directions, modify
elements, or access element indices.
Q26. What is a Map?
A Map in Java is an interface from the [Link] package designed to store data as key-
value pairs, where each unique key maps to exactly one value. Unlike other collections
such as List or Set, a Map does not allow duplicate keys, but values can be duplicated.
This structure enables efficient retrieval, insertion, and deletion of values based on their
associated keys.
Java Interview Cheat Sheet Page 42 of 57
Key Characteristics
• Key-Value Pair Storage: Each entry consists of a unique key and a value. Keys must
be unique, but values can repeat.
• No Duplicate Keys: Attempting to insert a duplicate key will overwrite the previous
value associated with that key.
• Null Handling: Depending on the implementation, Maps may allow one null key and
multiple null values (e.g., HashMap allows this, but Hashtable does not).
• Efficient Lookup: Maps provide fast access to values when the key is known.
• Not a Collection: Although part of the Java Collections Framework, Map does not
extend the Collection interface due to its unique structure and operations.
Core Methods
• put(K key, V value): Adds or updates a key-value pair.
• get(Object key): Retrieves the value for a given key.
• remove(Object key): Removes the mapping for a given key.
• containsKey(Object key): Checks if a key exists in the map.
• containsValue(Object value): Checks if a value exists in the map.
• size(): Returns the number of key-value pairs.
• clear(): Removes all mappings.
Collection Views
The Map interface provides three "views" for interacting with its contents:
• keySet(): Returns a set of all keys.
• values(): Returns a collection of all values.
• entrySet(): Returns a set of key-value pairs (entries).
Common Implementations
• HashMap: No guaranteed order, allows one null key and multiple null values, fast
access.
• LinkedHashMap: Maintains insertion order, slightly slower than HashMap.
• TreeMap: Maintains sorted order of keys, does not allow null keys.
Java Interview Cheat Sheet Page 43 of 57
• Hashtable: Synchronized, does not allow null keys or values.
Use Cases
• Counting occurrences (e.g., word frequency)
• Grouping data (e.g., products by category)
• Fast lookups by unique identifiers (e.g., user IDs)6
Java Interview Cheat Sheet Page 44 of 57
Concurrency
Q27. What is concurrency?
Concurrency refers to the ability of a program to execute multiple tasks simultaneously,
either truly at the same time (on multi-core processors) or by interleaving execution (on
single-core processors) through context switching. This allows Java applications to make
better use of system resources, improve performance, and remain responsive, especially
when handling complex or time-consuming operations.
Key Concepts
• Threads: The fundamental unit of concurrency in Java. Each thread represents a
separate path of execution within a program.
• Multithreading: A common way to achieve concurrency, where multiple threads run
within the same application, potentially sharing resources and objects.
• Parallelism: A subset of concurrency where tasks are actually executed at the same
time, typically on different CPU cores.
• Asynchronous Programming: Allows tasks to be performed without blocking the
main thread, further enhancing concurrency.
Benefits of Concurrency
• Improved Performance: By dividing tasks into smaller units that can be executed
independently, applications can run faster and more efficiently, especially on multi-
core hardware.
• Better Resource Utilization: Enables optimal use of CPU and memory by allowing
multiple operations to proceed without waiting for each other.
• Enhanced Responsiveness: Keeps applications responsive to user input, even
while performing lengthy operations.
• Simplified Modeling: Makes it easier to model real-world problems where multiple
activities occur simultaneously, such as in simulations or game engines.
Java Concurrency Tools and APIs
Java provides a robust set of concurrency tools and APIs, including:
• Core classes and interfaces: Thread, Runnable, Callable, Future
Java Interview Cheat Sheet Page 45 of 57
• High-level utilities: ExecutorService, thread pools, concurrent collections,
atomic variables (all in [Link] package).
Synchronization and Safety
Because threads may access shared resources, Java provides synchronization
mechanisms (such as the synchronized keyword and locks) to ensure thread safety and
prevent issues like race conditions.
Q28. What is a thread?
A thread is an independent path of execution within a program, allowing multiple tasks to
run concurrently. Every Java application starts with a main thread, and additional threads
can be created to perform tasks simultaneously, improving efficiency and
responsiveness—especially for operations like background processing, user interface
updates, or handling multiple client requests.
Key Points
• Definition:
A thread is a lightweight process, representing a separate flow of control in a Java
program. Multiple threads can run within the Java Virtual Machine (JVM) at the same
time, each with its own program counter, stack, and local variables.
• Purpose:
Threads enable concurrent programming, allowing a program to perform multiple
operations at once—such as responding to user input while processing data in the
background.
• Creation:
In Java, threads can be created in two main ways:
o By extending the Thread class and overriding its run() method.
o By implementing the Runnable interface and passing an instance to a
Thread object.
• Lifecycle:
Threads have a lifecycle that includes states like new, runnable, running, blocked,
and dead. The thread starts when its start() method is called, executes the code
in its run() method, and terminates when run() finishes.
Java Interview Cheat Sheet Page 46 of 57
• Concurrency and Synchronization:
Since threads may access shared resources, Java provides synchronization
mechanisms to prevent issues like race conditions and ensure thread safety.
• Use Cases:
Threads are commonly used for parallel tasks, such as handling multiple client
connections in a server, performing background computations, or keeping a user
interface responsive during long-running operations.
Q29. What is the difference between a process and a thread?
The main difference between a process and a thread in Java lies in their structure, resource
management, and how they execute tasks:
Process
• Definition: A process is an independent program in execution, with its own memory
space, system resources, and data.
• Isolation: Processes are isolated from each other. Each has its own address space
and resources, so one process cannot directly access the memory or data of
another.
• Resource Usage: Processes are heavyweight; creating and managing them requires
more system resources and overhead.
• Communication: Communication between processes (Inter-Process
Communication, IPC) is complex and slower, often involving files, sockets, or other
mechanisms.
• Failure Impact: If one process crashes, it does not directly affect others.
• Use Case: Running multiple independent applications or tasks that require strong
isolation.
Thread
• Definition: A thread is a lightweight, smaller unit of execution within a process.
Every process has at least one thread (the main thread), but can have many.
• Memory Sharing: Threads within the same process share the same memory space,
including heap and resources, but each has its own stack and program counter.
Java Interview Cheat Sheet Page 47 of 57
• Resource Usage: Threads are lightweight; creating and switching between threads
requires less overhead than processes.
• Communication: Threads can easily communicate with each other using shared
variables, but this requires careful synchronization to avoid conflicts.
• Failure Impact: If one thread fails (e.g., due to an unhandled exception), it can
potentially affect other threads in the same process.
• Use Case: Multithreading within a single application for parallelism, such as
handling multiple user requests or background tasks.
Summary Table
Aspect Process Thread
Memory Space Separate for each process Shared within the same
process
Resource High Low
Overhead
Communication Difficult, slower (IPC) Easy, faster (shared memory)
Isolation Strong (one process can't affect Weak (threads can affect each
another) other)
Creation Time Slower Faster
Use Case Independent applications Parallel tasks within an
application
Q30. What is multithreading?
Multithreading is a programming technique that allows multiple threads—small,
independent units of execution—to run concurrently within a single Java program. Each
thread represents a separate path of execution, enabling an application to perform
multiple tasks simultaneously.
Key Features of Multithreading in Java
• Concurrent Execution: Multiple threads can execute code at the same time, either
truly in parallel (on multi-core processors) or by rapidly switching between threads
(on single-core processors).
Java Interview Cheat Sheet Page 48 of 57
• Resource Sharing: Threads within the same process share memory and resources,
making communication between them efficient.
• Improved Performance: Multithreading can significantly enhance application
performance by utilizing CPU resources more efficiently, especially on multi-core
systems.
• Responsiveness: Applications remain responsive even during long-running tasks
because time-consuming operations can be moved to background threads.
• Simplified Modeling: Some problems, such as real-time processing, server request
handling, or GUI applications, are naturally modeled using multiple threads.
• Parallelism: Multithreading enables parallel processing, allowing independent
tasks to be executed simultaneously, which is especially beneficial for tasks that
can be divided into smaller units.
Advantages
• Better CPU Utilization: Keeps the CPU busy by running other threads while some
threads are waiting (e.g., for I/O operations).
• Faster Program Execution: Tasks can be completed more quickly by dividing work
among multiple threads.
• Enhanced User Experience: Applications are more interactive and responsive, as
heavy operations do not block the main thread.
• Scalability: Multithreaded programs can handle increased workloads more
efficiently.
Disadvantages
• Complexity: Writing, debugging, and maintaining multithreaded code is more
complex due to issues like synchronization, deadlocks, and race conditions.
• Synchronization Overhead: Managing access to shared resources can introduce
extra overhead and potential performance bottlenecks.
• Context Switching: Frequent switching between threads can consume CPU
resources and may reduce performance if not managed properly.
• Difficult Debugging: The concurrent nature of threads can make bugs harder to
reproduce and fix.
Java Interview Cheat Sheet Page 49 of 57
Example Use Cases
• Real-time systems (e.g., games, multimedia applications)
• Web servers handling multiple client requests
• Background processing in desktop or mobile applications
• Parallel data processing
Q31. What is the synchronized keyword?
The synchronized keyword is used to control access to shared resources by multiple
threads, ensuring that only one thread can execute a synchronized block or method at a
time. This mechanism prevents issues such as race conditions, where two or more threads
try to read and write shared data simultaneously, potentially leading to inconsistent or
incorrect results.
How It Works
• Synchronized Methods:
When a method is declared with the synchronized keyword, only one thread can
execute that method on a given object instance at a time. Other threads attempting
to call any synchronized method on the same object must wait until the current
thread finishes and releases the lock.
• Synchronized Blocks:
You can also use the synchronized keyword to lock only a specific block of code
within a method, rather than the entire method. This is useful for synchronizing only
the critical section that accesses shared resources, improving performance by
allowing more concurrency in other parts of the code.
• Locking Mechanism:
Java uses an internal monitor (or intrinsic lock) for synchronization. When a thread
enters a synchronized method or block, it acquires the lock associated with the
specified object. Other threads trying to acquire the same lock are blocked until it is
released.
Key Points
• Only one thread can hold the lock for a synchronized method or block at a time; all
others must wait.
Java Interview Cheat Sheet Page 50 of 57
• Synchronization can be applied to instance methods, static methods, or specific
code blocks.
• It ensures memory consistency, so changes made by one thread are visible to
others after the lock is released.
• Overusing synchronization can lead to performance bottlenecks and, if not
implemented carefully, to issues like deadlocks.
Summary
The synchronized keyword in Java is essential for thread safety when multiple threads
access shared data, ensuring that only one thread can execute a synchronized section at a
time, thus preventing data corruption and unpredictable behavior.
Q32. What is deadlock?
A deadlock is a situation in concurrent (multi-threaded) programming where two or more
threads are blocked forever, each waiting for the other to release a lock. This typically
happens when threads acquire multiple locks in different orders, leading to a cycle of
dependencies where no thread can proceed.
How Deadlock Occurs
Consider two threads, Thread 1 and Thread 2, and two resources (locks), A and B:
• Thread 1 acquires the lock on A and then tries to acquire the lock on B.
• Thread 2 acquires the lock on B and then tries to acquire the lock on A.
If Thread 1 holds A and waits for B, while Thread 2 holds B and waits for A, neither thread
can continue. Both are stuck waiting for the other to release the lock, resulting in a
deadlock.
Java Interview Cheat Sheet Page 51 of 57
Example
If Thread 1 locks lockA and Thread 2 locks lockB at the same time, both will wait
indefinitely for the other lock.
Characteristics of Deadlock
• Mutual Exclusion: At least one resource must be held in a non-shareable mode.
• Hold and Wait: A thread holds at least one resource and is waiting to acquire
additional resources held by other threads.
• No Preemption: Resources cannot be forcibly taken from threads; they must be
released voluntarily.
• Circular Wait: A set of threads are each waiting for resources held by the next
thread in the cycle.
Prevention Strategies
• Lock Ordering: Always acquire locks in a consistent, predefined order to avoid
circular wait.
• Timeouts: Use lock timeouts so threads don’t wait indefinitely.
Java Interview Cheat Sheet Page 52 of 57
• Minimize Lock Scope: Keep synchronized blocks as short as possible to reduce the
chance of deadlock.
• Use High-Level Concurrency Utilities: Prefer classes from
[Link] that are designed to minimize deadlocks.
Q33. What are the states of a thread?
A thread in Java can be in one of the following six states at any given time, as defined by the
Java Virtual Machine (JVM):
1. NEW
o The thread is created but has not yet started. This is the state after a Thread
object is instantiated but before the start() method is called.
2. RUNNABLE
o The thread is ready to run and is either currently running or waiting for CPU
time from the scheduler. In this state, the thread may be actively executing or
simply waiting its turn to execute.
3. BLOCKED
o The thread is blocked, waiting for a monitor lock (for example, trying to enter
a synchronized block/method that is locked by another thread). It cannot
proceed until the lock is released.
4. WAITING
o The thread is waiting indefinitely for another thread to perform a particular
action (such as calling [Link](), [Link](), or
[Link]()). It will remain in this state until it is notified or
interrupted.
5. TIMED_WAITING
o The thread is waiting for another thread to perform an action, but only for a
specified period of time (such as [Link](timeout),
[Link](timeout), or [Link](timeout)). After the
specified time, it will move back to RUNNABLE or another appropriate state.
Java Interview Cheat Sheet Page 53 of 57
6. TERMINATED
o The thread has finished execution; its run() method has completed, and it
cannot be started again.
Q34. What is the volatile keyword?
The volatile keyword in Java is a non-access modifier used primarily in multithreaded
programming to ensure visibility of changes to variables across threads. When a variable is
declared as volatile, it tells the Java Virtual Machine (JVM) that the variable's value will be
modified by different threads and must always be read from and written to the main
memory, not from a thread's local CPU cache.
Key Properties of volatile
• Visibility Guarantee:
When one thread updates a volatile variable, the new value is immediately visible to
all other threads. This prevents threads from seeing stale or inconsistent values due
to caching or compiler optimizations.
• No Atomicity:
Declaring a variable as volatile does not guarantee atomicity for compound
actions (like incrementing a counter). It only ensures visibility, not mutual exclusion
or indivisibility of operations.
• Lightweight Synchronization:
volatile is a lighter alternative to synchronized for cases where only visibility is
needed and not atomicity or mutual exclusion.
• Typical Use Cases:
o Flags or status indicators that are checked and updated by multiple threads
(e.g., a volatile boolean running flag to signal a thread to stop.
o Variables where it is critical that all threads see the most up-to-date value,
but where compound operations are not performed.
Java Interview Cheat Sheet Page 54 of 57
Stream API
Q35. What is the Stream API in Java?
The Stream API, introduced in Java 8, is a powerful framework for processing sequences of
elements (such as collections, arrays, or data from I/O channels) in a declarative,
functional programming style. Unlike traditional loops or iterators, the Stream API enables
you to filter, transform, and aggregate data through a pipeline of operations, resulting in
more readable and maintainable code.
Key Characteristics
• Declarative and Functional: Stream operations describe what should be done with
data, not how to do it, making code more concise and expressive.
• Non-destructive: Streams do not modify the original data source; instead, they
produce new streams or results.
• Lazy Evaluation: Intermediate operations (like filter or map) are not executed
until a terminal operation (like collect or forEach) is invoked. This enables
efficient, on-demand processing7.
• Support for Parallelism: Streams can be processed sequentially or in parallel,
leveraging multi-core architectures for improved performance on large datasets57.
• Pipeline Pattern: Stream operations can be chained together to form a processing
pipeline, typically consisting of a source, intermediate operations, and a terminal
operation17.
Common Stream Operations
• Intermediate Operations:
o filter(Predicate): Selects elements that match a condition.
o map(Function): Transforms each element.
o distinct(), sorted(), limit(n), etc.
o These are "lazy" and can be chained.
• Terminal Operations:
o forEach(Consumer): Performs an action for each element.
Java Interview Cheat Sheet Page 55 of 57
o collect(Collector): Converts the stream into a collection or another
form.
o reduce(BinaryOperator): Aggregates elements into a single result.
o These trigger the actual processing and consume the stream.
Example
This example filters names starting with "A", sorts them, and collects the result into a new
list.
Stream Sources
Streams can be created from:
• Collections (e.g., [Link]())
• Arrays (e.g., [Link](array))
• Static methods ([Link](), [Link](), [Link]())
• I/O channels (e.g., [Link](path))
Q36. What is the difference between map and flatMap in Streams?
Answer: The difference between map and flatMap in Java Streams lies in how they
transform and structure the data:
map
• Purpose: Transforms each element of a stream into another object, resulting in a
one-to-one mapping.
• Function Signature: Takes a function that returns a single value for each input.
• Result: Produces a new stream where each element corresponds to one element
from the original stream.
Java Interview Cheat Sheet Page 56 of 57
• Example: Converting a list of strings to their lengths:
• Typical Output: Stream<R>, where R is the result type.
flatMap
• Purpose: Transforms each element into a stream of values and then flattens all
resulting streams into a single stream, resulting in a one-to-many mapping.
• Function Signature: Takes a function that returns a stream (or collection) for each
input.
• Result: Flattens nested streams or collections into a single stream.
• Example: Flattening a list of lists into a single list:
• Typical Output: Stream<R>, but the function returns Stream<? extends R>,
and all these streams are merged into one.
Java Interview Cheat Sheet Page 57 of 57