Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Top 50 Java Interview Questions

Uploaded by

Zhou Crance
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Top 50 Java Interview Questions

Uploaded by

Zhou Crance
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Top 50 Java Interview Questions

1. What all does JVM Comprise of ?

–Classloader: The Classloader is the subsystem of the JVM responsible for loading class files.
You can explain that it loads all the required classes into memory when the program starts
running.
—Heap: The Heap is where objects are stored during the runtime of the program. It’s the area
of memory used for dynamic memory allocation, where Java objects and their associated data
are allocated.
—Method Area: The Method Area holds class-level information such as static variables,
constant pools, method data, and the code for methods. You should explain that it’s part of the
JVM’s memory that stores per-class structures.

—Stack: The Stack is used for storing method calls and local variables. Every time a method is
called, a new frame is created on the stack to store variables and track the method’s progress.
Each method call pushes a new frame, and when the method finishes, the frame is popped off.

—-Execution Engine: This is the component that reads and executes the bytecode of the Java
program. You should highlight that the execution engine can either interpret the bytecode line by
line or use the JIT (Just-In-Time) compiler to convert the bytecode into machine code for faster
execution.

—JNI (Java Native Interface): The JNI allows Java applications to interact with native
applications or libraries written in other languages like C or C++. This is useful when Java needs
to perform operations that depend on platform-specific features or external libraries.

2. What is object-oriented programming? Is Java an object-oriented language?

It's a programming paradigm based on the concept of objects. Objects are like containers that
hold both data (fields) and code (methods). These methods operate on the data within the
object, making it easier to access and modify.

In OOP, objects are created from classes, which act as blueprints that define the structure and
behavior of the objects. This helps organize code by linking data with the procedures that
operate on it, making programs more modular and easier to manage.

Some common OOP languages include C++, Java, Python, and JavaScript. These languages
allow you to model real-world entities as objects, providing a clear and efficient way to write
complex applications.
However, since Java uses eight primitive data types — boolean, byte, char, int, float, long,
short, and double — which are not objects, Java cannot be considered a 100% object-oriented
language.

3. What do you understand by Aggregation in context of Java?

It as a form of association where each object has its own lifecycle, but there is an ownership
relationship. The child object cannot belong to any other parent object.

Aggregation helps in reusing code by creating a relationship between two classes, often
described as a ‘has-a’ or ‘whole/part’ relationship. One class contains a reference to another,
and it's said to have ownership of that class.

These kinds of technical Java questions are designed to test your depth of knowledge, so avoid
giving a purely bookish definition. Instead, mention how aggregation is useful for building more
modular and maintainable systems.

4. Name the superclass in Java.

It's the root class for all non-primitive types in Java. Every class in Java either directly or
indirectly inherits from Object, making it a core part of the Java language.

The class defines important methods like equals(), hashCode(), and toString(), which are
universally used across the Java class hierarchy. By inheriting from Object, all classes gain a
common structure that supports interoperability, polymorphism, and object comparison.

Understanding java.lang.Object is essential because it underpins Java's inheritance model and


abstraction. Mastery of its role is key to leveraging the full power of Java’s object-oriented
programming features.

5. Explain the difference between ‘finally’ and ‘finalize’ in Java?

Finally Finalize
Used for exception handling Protected method java.lang.object

It is a block. It is a method.

Can be followed by try-catch/ without it. Can be explicitly called from an application
program.`

It is used to clean up the resources used in Clean up the activities related to the object
the ‘try’ block. before the destruction.

6. What is an anonymous inner class? How is it different from an inner class?

An anonymous inner class is a local inner class without a name, so it cannot have a constructor.
It either extends a class or implements an interface and is defined and instantiated in a single
statement.
It’s often used to override methods and can only implement one interface at a time.
An inner class is a non-static nested class associated with an instance of the outer class and
has access to all its methods and variables.

Some of the features of an anonymous class include-


● It is without any name.
● Only one object is created for it.
● It is used to override a method of a class.
● It can implement only one interface at a time.

7. What is a system class?

The System class is one of the core classes in Java, and it’s marked as final, which means you
can’t extend or inherit from it. Since it doesn’t provide any public constructors, you can’t
instantiate it either. All of its methods and fields are static, and it’s mainly used to access system
resources like standard input/output, environment variables, and properties.
It's a fundamental class, and understanding its role helps when working with system-level
operations in Java.

8. How to create a daemon thread in Java?

A daemon thread is a background thread in Java, typically used for tasks like garbage collection
or logging. To create a daemon thread, you call setDaemon(true) before invoking the start()
method; otherwise, you'll encounter an IllegalThreadStateException. Daemon threads are
designed to provide support to non-daemon (user) threads. The key difference is that they don’t
prevent the program from exiting—once all non-daemon threads finish, daemon threads
automatically terminate.

These threads are useful for background tasks that don’t need to complete if the main program
finishes, optimizing performance and resource utilization. By using daemon threads, developers
can ensure that important auxiliary tasks are handled efficiently without blocking the termination
of the main application.

9. Does Java support global variables? Why/Why not?

No, Java doesn’t support global variables. This is because global variables can lead to
namespace collisions, where multiple parts of a program might unintentionally use the same
variable name, leading to conflicts. Additionally, global variables break referential transparency,
which means functions or methods can become dependent on external states, making the
program harder to debug and maintain.

In Java, variables are typically scoped within classes, methods, or blocks, ensuring better
control over their use and preventing unintended side effects.
This explanation addresses the reasoning behind why Java avoids global variables and
demonstrates an understanding of scope and program design.

10. How is an RMI object developed?

To develop an RMI object in Java, you need to follow a series of steps:

1. Define the interface: Create an interface that declares the methods available for remote
invocation.
2. Implement the interface: Provide the concrete implementation of the methods defined in
the interface.
3. Compile the interface and implementation: Use the Java compiler to compile the
interface and its implementation.
4. Compile server implementation with RMI compiler: Use the RMI compiler (rmic) to
generate the necessary stub and skeleton classes.
5. Run the RMI registry: Start the RMI registry to bind the remote objects for client access.
6. Run the application: Start the server and client applications to allow remote method
calls.

By following these steps, developers can set up remote objects and enable communication
between distributed systems using RMI. This response clearly explains the RMI development
process, focusing on the steps and purpose of each, which is what the interviewer will be
looking for.

11. Explain the differences between time slicing and preemptive scheduling?

In time slicing, each task gets a fixed amount of time (a time slice) to execute. After its slice is
over, it moves to the ready queue, and the next task runs. This method is used for non-priority
scheduling, where all tasks share CPU time equally.

In preemptive scheduling, tasks are executed based on priority. The highest-priority task runs
until it completes or is preempted by an even higher-priority task.

This shows how the CPU manages threads in multithreading.

12. Garbage collector thread is what kind of a thread?

The garbage collector in Java is a daemon thread with low priority, running in the background. It
automatically manages memory by identifying and reclaiming unused objects, ensuring efficient
resource utilization. Since it’s a daemon thread, it doesn’t interfere with the main program’s
execution, silently freeing up memory to maintain smooth application performance.

This thread is crucial for Java's memory management, contributing to the language's efficiency
and reliability.

This version is concise, focusing on the garbage collector’s role as a daemon thread and its
importance in memory management.

13. What is the lifecycle of a thread in Java?

A thread in Java goes through several stages in its lifecycle:


● New: The thread is created but hasn’t started yet.
● Runnable: The thread is ready to run but might not be executing yet.
● Running: The thread is actively executing.
● Non-runnable (Blocked): The thread is alive but waiting for a resource or event.
● Terminated: The thread has finished executing.

This lifecycle outlines how a thread moves through different states during execution.

14. State the methods used during deserialization and serialization process.

● ObjectInputStream.readObject: This method reads from a file and deserializes the


object, converting it from its byte-stream back into a usable object in Java.
● ObjectOutputStream.writeObject: This method serializes an object and writes it to a file,
converting the object into a byte-stream for storage.

These methods are crucial for saving and retrieving object states in Java.

15. What are volatile variables and what is their purpose?

A volatile variable in Java ensures that its value is always read from the main memory, not from
a thread's cache. This is crucial for synchronization because it guarantees visibility of changes
across threads. The variable is declared with the volatile keyword to indicate that its value can
be modified by external factors.

Key features include:


● It's a field modifier.
● It improves thread performance by preventing caching.
● Volatile variables can’t cause a thread to block while waiting.
● They're not subject to compiler optimizations, ensuring consistent behavior across
threads.
This ensures that threads always have the most up-to-date value of the variable.

16. What are wrapper classes in Java?

In Java, every primitive data type has a corresponding wrapper class. These classes "wrap" a
primitive value into an object, allowing primitives to be treated as objects. This is essential when
working with frameworks or collections that require objects instead of primitives.

Key features include:


● Wrapper classes convert primitives into objects and vice versa.
● Java provides autoboxing (automatic conversion from primitive to object) and unboxing
(from object to primitive) to simplify these transformations.
This allows seamless interaction between primitives and objects in Java, enhancing flexibility in
coding.

17. How can we make a singleton class?

A singleton class ensures that only one instance of the class is ever created. To achieve this,
the constructor is made private, preventing external instantiation.

Other ways to enforce the singleton pattern include:


● Ensuring that only one instance of the class is created.
● Declaring all constructors private to block object creation outside the class.
● Providing a static method that returns the single instance of the class.
This pattern is commonly used for managing shared resources in an application.

18. What are the important methods of Exception Class in Java?

Java's Throwable class provides several key methods for handling exceptions and errors.

Some important methods include:

● String getMessage(): Returns a detailed message about the exception.


● String toString(): Returns a string representation of the exception.
● void printStackTrace(): Prints the stack trace of the exception to the console.
● synchronized Throwable getCause(): Returns the cause of the exception.
● public StackTraceElement[] getStackTrace(): Returns an array representing the stack
trace of the exception.
These methods are essential for debugging and understanding the nature of an exception. This
explanation is concise and covers the primary methods in the Throwable class, highlighting their
importance in exception handling.

19. How can we make a thread in Java?

There are two main ways to create a thread in Java:


1. By extending the Thread class: This involves creating a new class that extends Thread.
However, the downside is that since Java doesn’t support multiple inheritance, extending
Thread prevents you from extending any other class.
2. By implementing the Runnable interface: This is a more flexible approach, as it allows
your class to implement other interfaces or extend other classes. You define the run()
method and pass an instance to a Thread object.
The Thread class provides helpful methods and constructors to manage thread operations,
making it easier to start and manage threads.

20. Explain the differences between get() and load() methods.

The get() and load() methods in Hibernate are used to retrieve objects, but they behave
differently:
● get() returns null if the object isn’t found, whereas load() throws an
ObjectNotFoundException.
● get() always returns a real object, while load() returns a proxy object, which is a
placeholder for lazy initialization.
● get() immediately hits the database, but load() may delay the database hit until the
object is accessed.
● Use get() when you're unsure if the object exists, and load() when you're certain the
instance exists in the database.

21. What is the default value of the local variables?

In Java, local variables (declared inside methods) don’t automatically get a default value. Unlike
instance variables, which get values like 0 for numbers or null for objects, local variables must
be explicitly assigned a value before use. Both primitive types (like int) and object references
(like String) follow this rule. If you try to use a local variable without assigning it a value, the
compiler will throw an error.

This ensures that local variables are always properly initialized within the method or block where
they are used.

22. Define the class that remains superclass for each class?

The Object class is the superclass for all classes in Java. Every class, either directly or
indirectly, inherits from it. It provides essential methods like equals(), hashCode(), toString(),
and clone(), which can be used or overridden by any class.

23. What is the static method?

A static method in Java belongs to the class itself, not to any specific object. This means you
can call it directly using the class name, without having to create an instance of the class. Since
static methods are tied to the class, they can access and modify static variables, which are also
class-level (not tied to individual objects).

The main advantage of static methods is their ability to work with static data members, which
makes them efficient for tasks that involve class-wide data and don’t need to interact with
instance-specific details.

24. What is Exception handling ?

Exception handling in Java is a way for the program to manage errors that happen during
runtime. It helps the program deal with these errors smoothly without crashing. When an
exception occurs, Java allows you to catch and handle it, ensuring that the program can
continue running or gracefully recover from the issue.

This mechanism is useful for maintaining the normal flow of the program, even when
unexpected events, like invalid input or missing files, cause errors during execution.

Key components of exception handling include:

● try: Defines a block of code where exceptions may occur.


● catch: Catches and handles the exception.
● finally: Executes code after try-catch, regardless of whether an exception occurred,
often used for cleanup tasks.
● throw: Used to manually throw an exception.
● throws: Declares that a method may throw exceptions.

By using these mechanisms, Java ensures that errors are handled gracefully and the program
can recover or terminate safely.

25. In simple terms, how would you define Java?

Java is a high-level, platform-independent, object-oriented programming language known for its


"write once, run anywhere" (WORA) feature. This means that code written in Java can run on
any platform without needing modification. It enables developers to create robust applications,
websites, and complex programs with strong performance and cross-platform compatibility.

Java was created by James Gosling in 1991 and has become a core technology in the IT
industry. It is widely used to build versatile, powerful applications that work across different
systems and environments.

26. What is Java String Pool?


The String Pool is a special area in the Java Heap where string literals are stored. Since strings
in Java are immutable, meaning they can't be changed once created, this allows the String Pool
to store unique string values. This process is known as string interning, where identical string
literals share the same memory space, helping to optimize memory use.

When you create strings with double quotes, they utilize the String Pool. However, when using
the new keyword, a new string object is created outside the pool.

27. How would you define the meaning of Collections in Java?

Collections in Java are a framework that allows you to group multiple objects into a single unit,
making data storage and management easier. The Collections Framework provides a consistent
structure for working with different types of objects, enabling operations like sorting, searching,
adding, removing, and manipulating data.

It simplifies how developers handle groups of objects by offering ready-made interfaces and
classes, ensuring more efficient and organized data management across various types of
collections, such as lists, sets, and maps.

The key functions of Java Collections include:


● Sorting: Organizing elements in a particular order.
● Searching: Locating specific elements within a collection.
● Insertion: Adding elements to the collection.
● Manipulation: Modifying elements within the collection.
● Deletion: Removing elements from the collection.

Java Collections simplify data handling, offering a flexible and efficient way to manage groups of
objects.

28. Explain the OOPs concepts in Java.

Java’s OOP concepts—abstraction, polymorphism, inheritance, and encapsulation—are the


core principles that help developers build reusable, secure, and organized code.

● Abstraction hides internal details while exposing essential functionality to the user.
● Polymorphism allows objects to behave differently in different situations, with both
runtime and compile-time forms.
● Inheritance lets a subclass acquire properties and behaviors from a superclass,
promoting code reuse.
● Encapsulation wraps code and data together, using access modifiers to control visibility
and enhance security.
These OOP principles enable efficient and maintainable application development in Java.

29. Explain the two different types of typecasting?

There are two types of typecasting in Java:


1. Implicit Typecasting (widening): This is automatically done by the compiler when
converting a smaller data type to a larger one (e.g., int to long). It’s safe and doesn’t
result in data loss.
2. Explicit Typecasting (narrowing): This is manually done by the programmer when
converting a larger data type to a smaller one (e.g., double to int). It can lead to data loss
if the value doesn’t fit in the smaller type.

30. What is meant by Abstract class?

An abstract class in Java is defined using the abstract keyword and can contain both abstract
(incomplete) and non-abstract (complete) methods. Abstract classes provide a way to define
common behavior while leaving some implementation details to be specified by subclasses.

Key benefits of abstract classes include:

● Reducing complexity by focusing only on essential details.


● Enhancing security by controlling what details are exposed to users.
● Avoiding code duplication through shared behavior in subclasses.
● Increasing code reusability by allowing common methods to be used across different
subclasses.
● Changing internal implementation without affecting how the class is used externally.

Abstract classes help improve the structure, maintainability, and flexibility of Java applications.

31. Explain the difference between Abstraction and Encapsulation in Java.

Abstraction Encapsulation

Focuses on hiding complexity by Focuses on hiding data by bundling it into a


showing only the necessary details and single unit and controlling access.
functionality to the user.
Deals with the design level by using Deals with the implementation level by using
interfaces and abstract classes to define access modifiers (private, public, protected) to
what an object should do. restrict access to the object's data.

Helps to define what an object does, Ensures that the internal state of an object is
without exposing how it performs those protected and managed safely through getters
operations. and setters.

Example: Using an interface to define a Example: Using private variables in a class and
method without revealing the internal providing public getter and setter methods to
implementation. access them.

32. Write a Java Program to print Fibonacci Series using Recursion.

public class FibonacciRecursion {

// Recursive method to calculate Fibonacci number


public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
// Recursively call the fibonacci method
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


int terms = 10; // Number of terms in the Fibonacci series

System.out.println("Fibonacci Series up to " + terms + " terms:");


for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}

33. What is a garbage collection in Java?


In Java, objects are allocated in memory dynamically using the new operator. The deallocation
of memory is managed automatically by the Garbage Collection process. When an object is no
longer referenced or needed, the Garbage Collector frees up the memory it was using. This
ensures that unused objects don't take up space, without requiring manual memory
management from the programmer.

The primary goal of garbage collection is to:


● Improve memory efficiency by removing unused objects.
● Optimize memory management so that programs run smoothly without wasting
resources.

Garbage collection in Java simplifies memory management by keeping the system free from
unnecessary objects, ensuring that only active objects consume memory.

34. Why is Java considered platform-independent?

Java is platform-independent because of the Java Virtual Machine (JVM). When a Java
program is compiled, it’s converted into bytecode, which is platform-neutral and doesn’t depend
on any specific operating system. The JVM then interprets this bytecode and runs it on any
system, whether it's Windows, Linux, or Mac.

This design supports Java's philosophy of “write once, run anywhere”, meaning that Java
programs can be written once and executed on any platform that has a JVM, without needing to
recompile the code for each operating system.

35. Write a Java program to reverse a string?

import java.util.Scanner;

public class ReverseStringSimple {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

String reversedString = "";

for (int i = inputString.length() - 1; i >= 0; i--) {


reversedString += inputString.charAt(i);
}
System.out.println("Reversed string: " + reversedString);
}
}

36. Explain the use of ‘this’ keyword in Java?

In Java, the this keyword refers to the current object of the class. It helps the program
understand that you're talking about the current object's variables or methods. This is especially
useful when a method’s parameter has the same name as the class’s instance variable, so this
makes it clear you’re referring to the object’s variable.

You can also:


● Use this to pass the current object to other methods or constructors.
● Return this from a method to refer to the current object.
In short, this helps ensure that the program correctly uses the current object inside its class.

37. Explain the meaning of Inheritance.

In Java, Inheritance is a mechanism where one class, known as the subclass, inherits
properties and methods from another class, called the superclass. This allows the subclass to
reuse and extend the functionality of the superclass.

Key points about inheritance include:


● It lets you create new classes from existing ones.
● The subclass acquires all the properties and methods of the superclass.
● You can add new methods and fields to the subclass.
● Inheritance also allows for method overriding, where a subclass provides its own
implementation of a method in the superclass.

Inheritance is a powerful tool in Java, making code reusable and more maintainable.

38. Explain the meaning of interface.

In Java, multiple inheritance isn’t possible with classes, but interfaces solve this issue. An
interface allows a class to implement multiple behaviors, providing a form of abstraction and
loose coupling between modules. With recent Java updates, interfaces can now have default,
static, and private methods, giving them more flexibility.

Key benefits of interfaces include:


● They define behaviors that an object must implement.
● They act as a contract between the object and its code, ensuring consistency.
● Interfaces make it easier to modify implementations without affecting the overall system.
● They serve as connection points between different modules in a system.

Using interfaces in Java helps create more flexible and modular code.

39. Explain the meaning of Local variable and Instance variable?

A local variable is defined within a method, constructor, or block, and its scope is restricted to
that specific method or block. Once the method finishes executing, the local variable is no
longer accessible. These variables are not part of the object’s state and cannot be used outside
their defined block.

An instance variable, on the other hand, is declared inside a class but outside of any method.
Its scope extends across the entire class and is associated with an instance of the class. Each
object of the class has its own copy of the instance variables, and these variables represent the
object's state. They are accessible as long as the object exists, and their values can vary
between different instances of the same class.

40. What is a servlet?

Servlets are Java components that extend the capabilities of a web server. They run on Java-
powered web application servers and are designed to handle complex web requests. Servlets
provide benefits like high performance, scalability, portability, and security, making them a core
part of building Java web applications.

Servlet Process:
1. A user sends a request from the web browser.
2. The web server receives the request and forwards it to the appropriate servlet.
3. The servlet processes the request and generates a response.
4. The servlet sends the response back to the web server.
5. The web server then delivers the response to the browser, which displays the result to
the user.
Servlets rely on multiple classes and interfaces such as GenericServlet, HttpServlet,
ServletRequest, and ServletResponse, allowing them to interact with web requests and
responses efficiently.

41. What’s the exception?

An exception in Java refers to an unusual condition or event that occurs during the execution of
a program, often due to incorrect user input, programming errors, or other unforeseen issues.
When an exception occurs, it disrupts the normal flow of the program.
There are two main types of exceptions in Java:
1. Checked Exceptions: These are checked at compile time and must be either caught or
declared in the method signature.
2. Unchecked Exceptions: These occur at runtime and are typically due to logical errors
that are not caught by the compiler.

Java’s exception handling mechanism helps maintain the stability of the program by providing
ways to catch and handle these exceptions, preventing crashes.

42. What are the differences between constructors and methods?

Constructors vs Methods: Key Differences


● Function:
○ Constructor: Initializes an object when it's created. For example, in a Car class,
the constructor sets the car’s make, model, and year.
○ Method: Performs specific tasks after the object is created, like startEngine() in
the Car class.
● Invocation:
○ Constructor: Automatically invoked when using the new keyword to create an
object.
○ Method: Must be explicitly called, like car.startEngine().
● Execution:
○ Constructor: Runs only once when the object is created.
○ Method: Can be called multiple times during the object’s lifetime.
● Naming:
○ Constructor: Must have the same name as the class (Car() in the Car class).
○ Method: Can have any name that follows standard naming conventions
(startEngine()).
● Return Type:
○ Constructor: Has no return type.
○ Method: Must have a return type (void, int, etc.).

43. What are the key features of Exception Handling?

Key features of exception handling include:


● Responding to unexpected events that occur while the program runs.
● Preventing system crashes by properly managing exceptions.
● Java provides different ways to handle exceptions, such as throwing, catching, and
handling them using try, catch, and throw blocks.
44. What is the main difference between the notify() and notifyAll() method in Java?

The notify() method wakes up one randomly chosen thread from the waiting pool, while
notifyAll() wakes up all threads that are waiting.

In notify(), only one thread will proceed, leaving the rest in the waiting state. With notifyAll(), all
waiting threads are awakened, but only one will eventually get the lock, and the others will
continue waiting for their turn.

45. Which are the different lists available in the collection?

Java’s Collection Framework provides various types of lists to store and manage ordered
collections of objects. Some of the main list implementations include:

1. ArrayList: A resizable array that allows fast random access to elements. It is most
commonly used due to its flexibility.
2. LinkedList: A doubly-linked list, where each element is linked to its neighbors. It’s
efficient for insertions and deletions.
3. Vector: Similar to ArrayList but synchronized, meaning it is thread-safe.
4. Stack: A subclass of Vector, it implements a Last-In-First-Out (LIFO) stack of elements.

These lists provide different ways to manage and organize collections based on your needs,
whether you require fast access or efficient insertion and deletion.

46. Explain the Priority Queue.

A Priority Queue in Java extends the Queue interface and allows elements to be processed
based on their priority rather than just following the First-In-First-Out (FIFO) rule. You can
customize the priority using a Comparator or rely on the natural ordering of elements.

Key features of Priority Queue include:


● It helps in managing multiple tasks based on priority, especially in networking systems.
● It typically uses a heap data structure to maintain the priority order efficiently.
● It’s useful when tasks or elements need to be processed based on their relative
importance.

47. What is Multithreading?


Multithreading in Java allows a program to run multiple threads simultaneously, enabling it to
perform several tasks at once. Threads are lightweight and share the same memory space,
making the program more efficient with better performance and lower memory usage.

Key features of Multithreading include:


● It creates lightweight processes (threads).
● Multiple threads can run simultaneously, saving time and improving efficiency.
● Since threads are independent, if one thread is blocked or busy, it doesn’t stop other
threads from executing.

48. Can we force Garbage Collection?

When you're asked if we can force Garbage Collection in Java, the interviewer is testing your
understanding of Java's memory management.
No, Garbage Collection in Java is an automatic process handled by the JVM. While you can
request garbage collection by calling System.gc() or Runtime.gc(), you cannot force it to
happen. The JVM will decide when to perform garbage collection, and there's no guarantee that
calling these methods will immediately trigger it.

49. Explain the meaning of Object in Java?

An Object in Java is an instance of a class, representing real-world entities with specific state
and behavior. For example, a dog object might have states like name, breed, and color, and
behaviors like barking or wagging its tail.

In Java, an object is created using the new() keyword, which instantiates and initializes the
object. Each object has its own identity (unique existence), state (attributes or properties), and
behavior (actions it can perform).

50. Explain the importance of the finally block.

The finally block is crucial in Java because it always executes, whether an exception is handled
or not. It comes after the try or catch block and ensures that important code, such as closing
files or releasing resources, is always run. In the JVM, the finally block is executed just before
the program terminates or a file is closed.

Key points about the finally block:


● It is used to run important code (e.g., closing files, resource deallocation).
● It always runs, regardless of whether an exception was caught or not.
● There can only be one finally block for each try block.
● It ensures clean-up operations are performed in the program.

You might also like