Special Offer take any 4 courses for INR 21999.00*

Courses
0

Cambridge Shop

Core Java Interview Questions and Answers

Project Management

Edit Content

No FAQs found.

Edit Content

Use tools to detect leaks, avoid using static references unnecessarily, and properly close resources like streams and sockets.

While garbage collection frees memory automatically, frequent or poorly-timed collections can lead to performance lags (GC pauses).

Escape analysis determines the scope of object references to allocate them on the stack instead of the heap, reducing garbage collection overhead.

Use appropriate data structures, avoid unnecessary object creation, and minimize memory leaks by properly managing references.

The finalize() method is invoked before an object is garbage collected. It is rarely used and generally discouraged.

Tools like VisualVM, JConsole, and Eclipse MAT can monitor memory usage and identify memory leaks.

This error occurs when the JVM cannot allocate memory for an object because the heap is full and cannot be expanded.

Memory leaks occur when objects are no longer used but cannot be garbage collected due to lingering references.

The JMM defines how threads interact through memory and provides rules for reading and writing variables in a concurrent environment.

Soft references are used to refer to objects that should remain in memory until memory is low.
Weak references are cleared as soon as the object is no longer strongly reachable.

Metaspace stores class metadata and dynamically grows in size, unlike PermGen, which had a fixed size.

The PermGen (in earlier Java versions) stored metadata about classes, methods, and constants. It is replaced by the Metaspace in Java 8.

The PermGen (in earlier Java versions) stored metadata about classes, methods, and constants. It is replaced by the Metaspace in Java 8.

Minor GC cleans the Young Generation, while Major (or Full) GC cleans the entire heap, including the Old Generation.

The Old Generation holds long-lived objects that survived multiple garbage collection cycles.

The Old Generation holds long-lived objects that survived multiple garbage collection cycles.

The Young Generation stores newly created objects. It is divided into Eden and Survivor Spaces.

Garbage Collection automatically deallocates memory for objects that are no longer in use to prevent memory leaks.

The stack stores method-specific values like local variables and method calls. Each thread has its own stack.

The heap is used to store objects and class-level variables. It is divided into Young Generation, Old Generation, and sometimes Permanent Generation.

The JVM divides memory into the Heap, Stack, Method Area, Program Counter Register, and Native Method Stack.

Java Memory Management refers to the process of allocating and deallocating memory to objects dynamically to ensure optimal performance. It includes garbage collection and efficient use of heap and stack memory.

Concurrency involves multiple tasks making progress simultaneously, while parallelism executes multiple tasks at the same time using multiple processors.

A semaphore is a concurrency utility that controls access to a resource by maintaining a set number of permits.

A thread-safe program ensures that multiple threads can access shared resources without corrupting data or causing unexpected behavior.

The volatile keyword ensures that changes to a variable are visible to all threads, preventing issues caused by thread-local caches.

The Fork/Join framework is a parallelism tool introduced in Java 7 for breaking tasks into smaller sub-tasks (forking) and combining their results (joining).

ReentrantLock provides more advanced features, such as fair locking and interruptible waits, whereas synchronized is simpler and intrinsic to Java.

Callable is similar to Runnable but can return a result and throw exceptions. Future is used to represent the result of a computation performed by a thread.

The Executor framework is a utility for managing and controlling thread execution without directly managing thread creation. It provides thread pools and other concurrency tools.

Thread interference can be prevented using synchronization mechanisms like the synchronized keyword or higher-level concurrency utilities like ReentrantLock.

wait(): Releases the lock and waits until notified.
sleep(): Temporarily pauses execution but does not release the lock.

A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock.

Synchronized blocks allow you to lock only a specific section of the code instead of the entire method, improving performance.

Thread synchronization is the mechanism to control the access of multiple threads to shared resources, ensuring that only one thread can access a critical section at a time.

The start() method creates a new thread and executes the run() method in that thread. Calling run() directly will not create a new thread; it will execute in the current thread.

Important methods include start(), run(), sleep(), join(), yield(), interrupt().

The thread lifecycle includes the following states:
New
Runnable
Running
Blocked/Waiting
Terminated

A process is an independent execution unit with its own memory space, while a thread is a smaller unit within a process that shares memory with other threads of the same process.

Multithreading is achieved in Java using the Thread class or by implementing the Runnable interface.

Concurrency refers to the ability of a program to execute multiple tasks simultaneously, making efficient use of CPU.

Multithreading in Java is a feature that allows multiple threads to run concurrently within a program. Each thread represents an independent path of execution.

Frequent exception handling can degrade performance. Minimize this by validating inputs and avoiding unnecessary exception throwing.

Exceptions in threads can be handled using Thread.UncaughtExceptionHandler.

A subclass method can only throw the same exceptions or exceptions that are subclasses of those declared in the superclass method.

If an exception is thrown in a constructor, the object is not created, and the calling code must handle the exception.

Yes, since Java 7, multiple exceptions can be caught using a single catch block with a pipe (|).
try {
int result = Integer.parseInt(“abc”);
} catch (NumberFormatException | NullPointerException e) {
System.out.println(“Exception caught: ” + e);
}

Chained exceptions allow one exception to be linked with another. It is implemented using the Throwable class methods like initCause() and getCause().

If an exception occurs in the finally block, it may override exceptions from the try or catch blocks, potentially masking the original issue.

If an exception is not caught in the current method, it propagates up the call stack to the calling methods until caught or the program terminates.

No, a try block must be followed by either a catch block, a finally block, or both.

Exception: Recoverable issues (e.g., FileNotFoundException).
Error: Unrecoverable issues (e.g., StackOverflowError).

A custom exception is a user-defined exception created by extending the Exception class.
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

Yes, a method can have multiple catch blocks to handle different exception types.
try {
int[] arr = new int[2];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Index out of bounds!”);
} catch (Exception e) {
System.out.println(“Generic exception caught.”);
}

The catch block is skipped, and the finally block (if present) is executed.

The Throwable class is the root of all exceptions and errors in Java.

Yes, a finally block can execute with only a try block.

throw: Used to explicitly throw an exception.
throws: Declares the exceptions a method may throw.

The finally block executes code regardless of whether an exception is thrown or caught. It’s used for cleanup operations like closing files or releasing resources.

The try block contains code that may throw an exception, while the catch block handles the exception.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero!”);
}

Checked Exceptions: Checked at compile-time (e.g., IOException).
Unchecked Exceptions: Checked at runtime (e.g., ArithmeticException).
Errors: Critical issues not intended to be caught (e.g., OutOfMemoryError).

Exception Handling in Java is a mechanism to handle runtime errors, ensuring the program’s normal flow is not disrupted. It uses try, catch, finally, throw, and throws keywords.

Use the Collections.synchronizedList() or synchronizedMap() method to make a collection thread-safe.
Example:
List list = Collections.synchronizedList(new ArrayList());

Collections.sort() sorts a list of elements either in natural order or based on a custom comparator.

HashSet: Unordered, uses hashing.
TreeSet: Sorted, uses a Red-Black tree.

Fail-fast: Throw ConcurrentModificationException if the collection is modified during iteration (e.g., ArrayList).
Fail-safe: Allow modifications during iteration (e.g., CopyOnWriteArrayList).

PriorityQueue is a class implementing Queue where elements are processed based on priority (natural or custom order).

Comparable: Used for natural ordering (single sort sequence).
Comparator: Used for custom ordering (multiple sort sequences).

The Comparable interface is used to define a natural ordering for objects by implementing the compareTo() method.

HashSet: Does not maintain insertion order.
LinkedHashSet: Maintains insertion order.

TreeSet is a class implementing SortedSet that stores elements in ascending order. Use it when sorting is required, and duplicates are not allowed.

ConcurrentHashMap is a thread-safe implementation of HashMap. It uses segment-level locking to improve concurrency.

Iterator: Can traverse a collection in one direction.
ListIterator: Can traverse in both directions and modify the list during iteration.

ArrayList: Not synchronized, better performance in single-threaded environments.
Vector: Synchronized, thread-safe but slower.

HashMap: Not synchronized, allows null keys/values.
Hashtable: Synchronized, does not allow null keys/values.

HashMap is a class implementing the Map interface. It stores key-value pairs using hashing. Each key’s hash code determines the bucket for storage, ensuring fast retrieval.

ArrayList: Resizable array, faster for random access.
LinkedList: Doubly-linked list, faster for insertions/deletions.

List: Allows duplicate elements and maintains insertion order (e.g., ArrayList, LinkedList).
Set: Does not allow duplicates and may not maintain order (e.g., HashSet, TreeSet).

Collection: Interface representing a group of objects.
Collections: Utility class providing methods like sort(), shuffle(), etc.

List
Set
Map
Queue
Deque
SortedSet
SortedMap

Reusability: Provides reusable data structures and algorithms.
Efficiency: Optimized performance for data operations.
Flexibility: Supports dynamic data storage.
Interoperability: Collection interfaces promote easy interaction between different types.

The Collections Framework in Java is a set of classes and interfaces in java.util package designed to handle a group of objects. It provides standard data structures such as List, Set, Map, and Queue, along with algorithms like sorting and searching.

Access modifiers control the visibility of class members:
Public: Accessible everywhere.
Private: Accessible only within the class.
Protected: Accessible within the package and by subclasses.
Default: Accessible within the package .

Constructors are special methods used to initialize objects. They have the same name as the class and do not have a return type.

Abstraction hides implementation details and shows only essential features. It is achieved using abstract classes or interfaces .

Overloading: Same method name but different parameters (Compile-time).
Overriding: Same method signature but in a child class (Runtime).

Polymorphism allows methods to have multiple forms.
Compile-time Polymorphism: Achieved via method overloading.
Runtime Polymorphism: Achieved via method overriding .

Encapsulation restricts direct access to class members by using private modifiers and allows controlled access via public getter and setter methods.
Example:
class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

Class: A blueprint or template for creating objects.
Object: An instance of a class containing data (attributes) and methods (functions).

OOP: Uses objects to design applications and emphasizes reusability.
SOP: Focuses on functions and procedures, with less focus on reusability.

Encapsulation: Bundling data and methods into a single unit (class).
Inheritance: Deriving a new class from an existing class.
Polymorphism: Allowing a method to behave differently based on the object.
Abstraction: Hiding implementation details and exposing only essential features .

OOP is a programming paradigm based on the concept of “objects” that encapsulate data and behavior. It emphasizes reusability, scalability, and efficiency using principles like inheritance, encapsulation, polymorphism, and abstraction .

The JVM handles multithreading by providing thread-safety in:
Heap: Shared among threads, synchronized for concurrent access.
Stack: Thread-local; each thread has its own stack. Additionally, JVM uses locks, thread pooling, and scheduling to manage threads.

A memory leak occurs when objects are no longer used but are still referenced, preventing garbage collection. It can be detected using profiling tools like VisualVM or JConsole.

Serial GC: Single-threaded; suitable for small applications.
Parallel GC: Multi-threaded; balances throughput and latency.
CMS (Concurrent Mark-Sweep) GC: Reduces pause times; works concurrently.
G1 GC (Garbage-First): Divides the heap into regions; optimizes for large heaps.

Adjusting Heap size with -Xms and -Xmx flags.
Optimizing Garbage Collector behavior using -XX options.
Enabling JIT optimizations with proper JVM settings.
Profiling and reducing memory allocation.

Garbage Collection (GC) is an automatic memory management process in JVM that identifies and removes unused objects to free up memory. It ensures efficient memory usage and prevents memory leaks.

The Just-In-Time (JIT) Compiler translates bytecode into native machine code during runtime, improving execution speed by optimizing frequently executed code paths (hotspots).

JVM memory is divided into:
Heap: Stores objects and class instances.
Method Area: Stores class structure (e.g., methods, constants).
Stack: Stores method-specific values like local variables and partial results.
Program Counter (PC): Tracks the address of the current instruction.
Native Method Stack: Supports native (non-Java) method execution.

The Classloader dynamically loads Java classes into the JVM during runtime. It follows a delegation hierarchy: Bootstrap Classloader, Extension Classloader, and Application Classloader.

The Classloader dynamically loads Java classes into the JVM during runtime. It follows a delegation hierarchy: Bootstrap Classloader, Extension Classloader, and Application Classloader.

The main components of the JVM include:
Classloader: Loads class files.
Bytecode Interpreter: Executes Java bytecode.
Just-In-Time (JIT) Compiler: Converts bytecode to machine code for better performance.
Garbage Collector (GC): Manages memory by cleaning up unused objects.
Runtime Data Areas: Includes Heap, Method Area, Stack, PC Register, and Native Method Stack.

The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run Java programs. It converts Java bytecode into machine-specific instructions, enabling platform independence. The JVM also includes memory management, garbage collection, and security features.

The JVM handles multithreading by providing thread-safety in:
Heap: Shared among threads, synchronized for concurrent access.
Stack: Thread-local; each thread has its own stack. Additionally, JVM uses locks, thread pooling, and scheduling to manage threads.

A memory leak occurs when objects are no longer used but are still referenced, preventing garbage collection. It can be detected using profiling tools like VisualVM or JConsole.

The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run Java programs. It converts Java bytecode into machine-specific instructions, enabling platform independence. The JVM also includes memory management, garbage collection, and security features.

JDK (Java Development Kit): Includes tools for developing Java applications (e.g., compiler, debugger).
JVM (Java Virtual Machine): Executes Java bytecode on different platforms.
JRE (Java Runtime Environment): Provides the libraries and JVM required to run Java applications.

Java is considered platform-independent because its compiled bytecode can run on any platform with a Java Virtual Machine (JVM). This bytecode eliminates the need for recompilation on different platforms, making Java portable and versatile

Writing a Simple “Hello World” Program in Java
Set up Java Environment:
Install the Java Development Kit (JDK) and set up the environment variables (e.g., JAVA_HOME).
Install a text editor or IDE (like Notepad++, Eclipse, or IntelliJ IDEA).
Write the Program:
Open your text editor or IDE and create a new file named HelloWorld.java.
Enter the following code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Save the File:
Save the file with the exact name as the class name, HelloWorld.java.
Compile the Program:
Open the terminal or command prompt.
Navigate to the directory where HelloWorld.java is saved.
Run the command:javac HelloWorld.java
This generates a HelloWorld.class file.
Run the Program:
Run the compiled program using the command:You should see the output:
Copy code
Hello, World!
Code Explanation:
public class HelloWorld: Declares a public class named HelloWorld.
public static void main(String[] args): The main method where execution begins.
System.out.println(“Hello, World!”);: Prints “Hello, World!” to the console.
This is the simplest way to start learning Java programming

Edit Content

A tool for profiling and monitoring Java applications.

It provides detailed messages about what caused the NullPointerException.

List.of creates immutable lists:
List list = List.of(“a”, “b”, “c”);

Collectors.teeing combines two collectors and applies a finishing function:

A Record is a special class for modeling immutable data:
public record Point(int x, int y) {}
Point point = new Point(10, 20);
System.out.println(point.x());

Compact number formatting represents numbers in a human-readable format (e.g., “1K” for 1000). Example:NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
System.out.println(formatter.format(1000)); // 1K

if (obj instanceof String str) {
System.out.println(str.length());
}

Text blocks allow multi-line string literals without explicit newline or concatenation:
String text = “””
Line 1
Line 2
Line 3
“””;
System.out.println(text);

ZGC (Z Garbage Collector) is designed for low-latency and high scalability, maintaining very short GC pauses (<10ms) regardless of heap size.

The isEmpty method returns true if the Optional is empty, simplifying null checks.

Switch expressions allow the switch statement to return a value and support lambda-like syntax:
int day = switch (input) {
case 1, 2, 3 -> input + 10;
default -> 0;
};

Files.writeString(Path.of(“file.txt”), “Hello World”);
String content = Files.readString(Path.of(“file.txt”));
System.out.println(content);

Sealed classes allow you to define a restricted class hierarchy. A sealed class can only be extended by explicitly permitted classes.

The HttpClient API simplifies making HTTP requests. It supports synchronous and asynchronous programming and includes features like HTTP/2 support and WebSocket communication.

Java 11 added several String methods:
isBlank(): Checks if a string is empty or contains only white spaces.
lines(): Returns a stream of lines split by line terminators.
strip(): Removes leading and trailing white spaces.
repeat(int count): Repeats the string.

The var keyword allows local variable type inference, meaning the compiler determines the type based on the assigned value. Explicit type declarations require developers to specify the type manually. Example:
var number = 10; // Compiler infers as int
int number = 10; // Explicit declaration

Examples of unsupervised learning algorithms include:
K-Means clustering
Hierarchical clustering
Principal Component Analysis (PCA)
Autoencoders

Submit an interview question

    Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Cambridge Infotech.



    Flyers
    Movers
    Starters

    All fields are required. By clicking the button, you agree with the Terms and Conditions of Cambridge Infotech’s Privacy Policy.

    Drop a Query

    Whether to upskill or for any other query, please drop us a line and we'll be happy to get back to you.

    Drop a Query NEW

    Request A Call Back

    Please leave us your contact details and our team will call you back.

    Request A Call Back

    By tapping Submit, you agree to Cambridge infotech Privacy Policy and Terms & Conditions

    Enroll New Course Now

    Enquiry Now

    Enquiry popup