Java Collections Q&A
Java Collections Q&A
Array:
Arrays are fixed in size, meaning once you define the size of an array, it cannot
be changed.
Arrays can hold both primitive data types and objects.
Arrays can store elements of the same type.
Collection:
Collections are dynamic in size; they can grow or shrink during the execution of a
program.
Collections can only hold objects, not primitive data types.
Collections provide a set of classes and interfaces to work with groups of objects.
Q) Name the core Collection interfaces & their implementing Collection classes
Root Interface:
Collection Interface:
Methods:
add(E e)
addAll(Collection<? extends E> c)
remove(Object o)
removeAll(Collection<?> c)
size()
clear()
isEmpty()
contains(Object o)
containsAll(Collection<?> c)
toArray()
iterator()
Q) Explain the difference between ArrayList & Vector
ArrayList:
Not synchronized by default.
Increases its size by 50% of the array size when resizing.
Not legacy (introduced in Java 2).
Vector:
Synchronized by default.
Increases its size by doubling when resizing.
Legacy class (introduced in Java 1.0).
ArrayList & LinkedList
ArrayList:
Implements dynamic arrays.
Faster for random access.
Slower for insertions and deletions.
LinkedList:
Implements a doubly-linked list.
Faster for insertions and deletions.
Slower for random access.
HashSet & TreeSet
HashSet:
Does not maintain any order.
Uses hashCode() for storing elements.
TreeSet:
Maintains natural order or order specified by a comparator.
Uses a red-black tree for storing elements.
HashSet & HashMap
HashSet:
Implements the Set interface.
Stores elements using a hash table.
HashMap:
Implements the Map interface.
Stores key-value pairs using a hash table.
Hashtable & HashMap
Hashtable:
Synchronized (thread-safe).
Does not allow null keys or values.
HashMap:
Not synchronized by default.
Allows null keys and values.
HashMap & TreeMap
HashMap:
Does not maintain order.
Faster for most operations.
TreeMap:
Maintains natural order or order specified by a comparator.
Slower for most operations compared to HashMap.
Iterator & ListIterator
Iterator:
Supports only forward iteration.
Can be used with any collection.
ListIterator:
Supports bidirectional iteration.
Specific to lists.
Iterator & Enumeration
Iterator:
Introduced in Java 1.2.
Supports both read and remove operations.
Enumeration:
Introduced in Java 1.0.
Supports only read operations.
Set & List
Set:
Does not allow duplicate elements.
Examples: HashSet, TreeSet.
List:
Allows duplicate elements and maintains order.
Examples: ArrayList, LinkedList.
Set & Map
Set:
Represents a collection of distinct elements.
Examples: HashSet, TreeSet.
Map:
Represents a collection of key-value pairs.
Examples: HashMap, TreeMap.
Queue and Stack
Queue:
Follows the FIFO (First-In-First-Out) principle.
Examples: LinkedList, PriorityQueue.
Stack:
Follows the LIFO (Last-In-First-Out) principle.
Examples: Stack class.
Queue & List
Queue:
Specifically designed for holding elements prior to processing.
List:
Designed for ordered collections with index-based access.
Collection and Collections
Collection:
Represents a group of objects.
Root interface for collections framework.
Collections:
A utility class providing static methods for operating on collections.
Comparable and Comparator
Comparable:
An interface used for natural ordering of objects.
The compareTo method is implemented by the class itself.
Comparator:
An interface used for custom ordering of objects.
The compare method is implemented in a separate class.
Q) What is the difference between Array and ArrayList?
Array:
Fixed size.
Can contain both primitive types and objects.
Direct access to elements using index.
ArrayList:
Dynamic size (can grow or shrink).
Can only contain objects.
Elements accessed using methods like get().
Q) Why do we override the equals() & hashcode() method?
equals():
Used to compare the equality of objects.
Should be overridden to provide a meaningful comparison for custom classes.
hashCode():
Used by hash-based collections (e.g., HashMap, HashSet).
Should be overridden consistently with the equals() method.
Q) How to synchronize List, Set, and Map elements?
List:
java
Copy code
List<Type> synchronizedList = Collections.synchronizedList(new ArrayList<>());
Set:
java
Copy code
Set<Type> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
Map:
java
Copy code
Map<KeyType, ValueType> synchronizedMap = Collections.synchronizedMap(new
HashMap<>());
Q) What is the advantage of generic collection?
Advantages:
Type safety: Ensures compile-time type checking.
Code readability: Makes code more readable by explicitly specifying the type of
elements.
Eliminates casting: No need for explicit casting when retrieving elements.
Q) How to convert ArrayList to Array and Array to ArrayList?
ArrayList to Array:
java
Copy code
ArrayList<Type> list = new ArrayList<>();
Type[] array = list.toArray(new Type[list.size()]);
Array to ArrayList:
java
Copy code
Type[] array = // existing array
ArrayList<Type> list = new ArrayList<>(Arrays.asList(array));
Q) How to reverse ArrayList?
java
Copy code
Collections.reverse(arrayList);
Q) How to sort ArrayList?
java
Copy code
Collections.sort(arrayList);
Q) Which collection classes are synchronized or thread-safe?
Synchronized Classes:
Vector
HashTable
Collections.synchronizedList(List<T> list)
Collections.synchronizedSet(Set<T> set)
Collections.synchronizedMap(Map<K, V> map)
Q) What is the difference between peek(), poll(), and remove() methods of the Queue
interface?
peek():
java
Copy code
// Insertion
HashMap<KeyType, ValueType> hashMap = new HashMap<>();
hashMap.put(key1, value1);
hashMap.put(key2, value2);
// Retrieval
ValueType retrievedValue = hashMap.get(key1);
// Deletion
hashMap.remove(key1);
Q) What is the difference between HashMap and ConcurrentHashMap?
HashMap:
Not synchronized, not thread-safe.
Faster in a single-threaded environment.
ConcurrentHashMap:
Synchronized, thread-safe.
Supports concurrent updates without blocking the entire map.
Better performance in a multi-threaded environment.
Q) Why does the Map interface not extend the Collection interface in the Java
Collections Framework?
Reasons:
Semantical differences: Maps store key-value pairs, while collections store
individual elements.
Operations: Maps have key-based operations (e.g., get(key), put(key, value)) not
applicable to general collections.
Q) Write the code for iterating the list in different ways in Java?
java
Copy code
List<Type> list = new ArrayList<>();
// Using Iterator
Iterator<Type> iterator = list.iterator();
while (iterator.hasNext()) {
Type element = iterator.next();
// Process element
}
// Using ListIterator (for lists only)
ListIterator<Type> listIterator = list.listIterator();
while (listIterator.hasNext()) {
Type element = listIterator.next();
// Process element
}
Q) Steps to sort objects in ArrayList using the employeeId attribute in the
Employee class:
java
Copy code
public class Employee implements Comparable<Employee> {
// Other attributes and methods
@Override
public int compareTo(Employee otherEmployee) {
return Integer.compare(this.employeeId, otherEmployee.employeeId);
}
}
Use Collections.sort() to sort the ArrayList.
java
Copy code
List<Employee> employees = new ArrayList<>();
// Add employees to the list
Collections.sort(employees);
Q) How can an ArrayList be synchronized without using Vector?
java
Copy code
List<Type> synchronizedList = Collections.synchronizedList(new ArrayList<>());
Q) What is NavigableMap in Java? What is the benefit over Map?
NavigableMap:
PriorityQueue:
Implements a priority queue, which is based on the priority heap.
Elements are ordered based on their natural order or according to a specified
comparator.
The head of the queue is the least element according to the specified ordering.
Q)What is an inner class?What are the advantages of Inner classes?
Q)What are the different types of inner classes?
Q)Can we access all the members of outer class inside a member inner class?
Q)What are non static inner classes?
Q)Can we access non-static members of outer class inside a static nested class?
Q)Can member inner classes have static members in them?
Q)Can we declare local inner classes as private or protected or public?
Q)What is the main difference between static and non-static nested classes?
Q)What are the advantages of Inner classes?
Q)If you compile a file containing inner class how many .class files are created
and
what are all of them accessible in usual way?
Q)How to access the inner class from code within the outer class?
Q)What is a nested interface ?
Q)Explain Method Local Inner Classes ?
Q) How is local inner class different from anonymous class and which one you should
chose?
Q)Can you define constructors for inner classes?
Inner Class:
An inner class is a class that is defined within another class in Java. It is a way
of logically grouping classes that are only used in one place, making the code more
readable and maintainable.
Encapsulation: Inner classes can access private members of the outer class,
promoting encapsulation.
Code Organization: Inner classes help in organizing code by keeping related classes
together.
Improved Readability: Inner classes enhance code readability by keeping closely
related classes in a single place.
Accessibility: Inner classes can access private members of the outer class,
providing better encapsulation.
Event Handling: Inner classes are often used for event handling in GUI
applications.
Q) What are the different types of inner classes?
Member Inner Class (Non-static Inner Class): A class defined within another class
without the static modifier.
Static Nested Class (Static Inner Class): A static class defined within another
class.
Local Inner Class: A class defined within a method.
Anonymous Inner Class: A class defined without a name.
Q) Can we access all the members of the outer class inside a member inner class?
Yes, a member inner class can access all the members (including private) of its
outer class.
Non-static inner classes, also known as member inner classes, are classes defined
within another class without using the static modifier. They have access to the
instance variables and methods of the outer class.
Q) Can we access non-static members of the outer class inside a static nested
class?
No, a static nested class (static inner class) cannot directly access non-static
members of the outer class. It can only access static members.
Yes, member inner classes can have static members, including static fields and
methods.
Yes, local inner classes can be declared with any access modifier (private,
protected, public, or default package-private). However, the scope of a local inner
class is limited to the block where it is defined.
Q) What is the main difference between static and non-static nested classes?
For each inner class, a separate .class file is generated. The files are named as
follows:
Q) How to access the inner class from code within the outer class?
To access the inner class from within the outer class, you can simply use the inner
class name prefixed with the outer class name followed by a dot. For example:
java
Copy code
public class OuterClass {
class InnerClass {
// Inner class code
}
java
Copy code
public class OuterClass {
public void methodWithLocalClass() {
class LocalInnerClass {
// Local inner class code
}
Yes, both member inner classes and static nested classes can have constructors.
Local inner classes and anonymous inner classes cannot have explicit constructors,
but they can use instance initialization blocks for initialization.
The default access specifier (also known as package-private) means that the class,
method, or variable is only accessible within the same package. It is not visible
to classes in other packages.
Q) Can I import the same package/class twice? Will the JVM load the package twice
at runtime?
Yes, you can import the same package or class twice in a Java program, but it will
not have any impact on the runtime behavior. The JVM will not load the package or
class twice. Import statements are just a compile-time directive for the compiler
to resolve names.
No, you don't need to import classes from the java.lang package explicitly. Classes
in java.lang are automatically imported by default in every Java program.
public class:
A class with the public modifier can be accessed from any other class.
It allows other classes to instantiate and use the class.
class:
A class without an access modifier (default access) is accessible only within the
same package.
It has package-private access, meaning it can be used by other classes in the same
package but not outside.
Q) Name a few classes that are part of the following packages:
java.io:
No, importing a package using a wildcard (*) only imports classes from that
specific package, not its sub-packages. If you want to import classes from sub-
packages, you need to import them explicitly.
Q) What is a JAR file? What happens when we add an external JAR file to an Eclipse
project using the build path?
JAR file:
A JAR (Java Archive) file is a compressed file format that allows bundling multiple
Java files, resources, and metadata into a single file.
It is a way to distribute a set of Java classes and associated metadata.
Adding external JAR file to Eclipse:
When you add an external JAR file to an Eclipse project using the build path, the
classes and resources from the JAR file become available for use in your project.
Eclipse includes the JAR file in the classpath, allowing your project to reference
and use the classes from the JAR.
Q) What is the difference between path vs. classpath?
Path:
The path is an environment variable that specifies the directories where executable
files are located.
It helps the operating system locate executables.
Classpath:
A fully qualified classname is the complete name of a class, including its package
name. For example, java.util.ArrayList is a fully qualified classname.
Q) How will you use two classes having the same name in a Java program?
To use two classes with the same name in a Java program, you should use their fully
qualified classnames when referencing them in your code. For example:
java
Copy code
com.example.ClassName obj1 = new com.example.ClassName();
otherpackage.ClassName obj2 = new otherpackage.ClassName();
Q) What environment variables do we need to set to run Java?
JAVA_HOME:
public
abstract
final
strictfp
Q) What is the difference between importing "java.applet.Applet" and "java.applet.
"?*
import java.applet.Applet;:
Imports only the Applet class from the java.applet package.
You need to reference Applet by its simple name.
import java.applet.*;:
Yes, an interface can be placed in a package like any other class. Here's an
example:
java
Copy code
package com.example;
"
1.Consider following program. When is the B object, created in line 3, eligible for
garbage collection?
void testMethod()
{
A aObj = new A();
BbObj = new B();
aObj.aMethod(bObj);
aObj=null;
bObj=null;
System.out.println(“Completed”);
}
after line 5"
Q)Which part of the memory is involved in Garbage Collection? Stack or Heap?
Q)What is the purpose of garbage collection in Java, and when is it used ?
Q)What does System.gc() and Runtime.gc() methods do ?
Q)Can the Garbage Collection be forced by any means?
Q)When is the finalize() called ? What is the purpose of finalization ?
Q)How to enable/disable call of finalize() method of exit of the application
Q) When does an Object becomes eligible for Garbage collection in Java
Q) Is garbage collector a daemon thread?
Q)what is Islands of Isolation?
Q)What is difference between final, finally and finalize?
Q)Explain Garbage collection mechanism in Java? GC Phases?
Garbage Collection primarily involves the Heap memory. Objects created on the heap
are subject to garbage collection when they are no longer reachable.
Both System.gc() and Runtime.gc() are used to suggest to the JVM that it should
perform garbage collection. However, there is no guarantee that the garbage
collection will actually occur.
The call to the finalize() method on exit of the application can be controlled
using the following options:
Enable: System.runFinalizersOnExit(true);
Disable: System.runFinalizersOnExit(false);
However, the use of runFinalizersOnExit is discouraged due to potential issues, and
it has been deprecated in recent Java versions.
An object becomes eligible for garbage collection when there are no more references
to it. This can happen when all references to the object go out of scope, are
explicitly set to null, or are overridden by new references.
final:
Mark: Identifying reachable objects by traversing the object graph starting from
root objects (like main method arguments, thread stacks, static variables).
Sweep: Identifying and reclaiming memory occupied by unreachable objects.
Compact: Rearranging memory to reduce fragmentation (not always performed).
The Java HotSpot VM uses different garbage collection algorithms, including the
Young Generation (Minor GC) and the Old Generation (Major GC/Full GC). Young
Generation garbage collection involves the Eden space and two survivor spaces,
while Old Generation garbage collection targets long-lived objects.
GC algorithms include:
Multithreading in Java:
Multithreading is a concurrent execution of two or more threads. It allows multiple
threads to execute simultaneously within a single program.
Advantages of Multithreading:
scss
Copy code
New → Runnable → (Blocked, Waiting, Timed Waiting) → Terminated
Q) What is the difference between Thread and Process in Java?
Thread:
Implementing Runnable:
Does not allow multiple inheritance (Java does not support multiple class
inheritance).
May be simpler if the main goal is to create a simple thread without extending
other classes.
Q) What is the difference between starting a thread with the run() and start()
method?
run() method:
Executes the thread's code in the current thread, not creating a new thread.
No parallelism, as it runs in the same thread.
start() method:
Creates a new thread and executes the thread's code in that new thread.
Enables parallelism, as the new thread runs concurrently.
Q) Can you again start a Thread? What will happen if we do it?
Once a thread has completed its execution, it cannot be restarted. If you attempt
to start a thread again, it will throw a java.lang.IllegalThreadStateException.
Q) How can you ensure all threads that started from the main must end in the order
in which they started, and also the main should end last?
You can use the join() method to ensure that a thread completes its execution
before the next one starts. For example:
java
Copy code
Thread t1 = new MyThread();
Thread t2 = new MyThread();
t1.start();
t1.join(); // Ensures t1 completes before t2 starts
t2.start();
t2.join(); // Ensures t2 completes before the main thread proceeds
Q) What is a daemon thread? How to make a thread (user thread) a daemon thread?
A daemon thread is a background thread that runs in the background and does not
prevent the program from terminating. You can set a thread as a daemon using the
setDaemon(true) method before starting it. For example:
java
Copy code
Thread daemonThread = new MyThread();
daemonThread.setDaemon(true);
daemonThread.start();
Q) What is the difference between a user thread and a Daemon thread?
User Thread:
Thread safety refers to the ability of a piece of code to function correctly and
consistently in a multithreaded environment. A thread-safe class is designed to be
safely used by multiple threads without causing data corruption.
Vector is a thread-safe class because its methods are synchronized, making it safe
for concurrent access by multiple threads. However, in modern Java, it is often
recommended to use ArrayList or Collections.synchronizedList() for thread safety
instead of Vector.
A race condition occurs when two or more threads access shared data concurrently,
leading to unpredictable and undesirable results. To solve race conditions,
synchronization mechanisms such as locks (synchronized keyword),
java.util.concurrent classes, or other coordination mechanisms can be used to
ensure that only one thread can access critical sections of code at a time.
Exiting run() method: Simply returning from the run() method will cause the thread
to exit.
Using a flag: Use a boolean flag to indicate when a thread should stop, and check
it periodically in the run() method.
Interrupting the thread: Use the interrupt() method to signal a thread to stop. It
is often combined with checking Thread.interrupted() or isInterrupted().
Q) How do threads communicate between each other?
notify():
Wakes up one of the threads that are currently waiting on the object.
It may not be deterministic which thread is awakened.
notifyAll():
Wakes up all the threads that are currently waiting on the object.
Safer to use in scenarios where multiple threads need to be awakened.
Q) Why are wait(), notify(), and notifyAll() in the Object class and not in the
Thread class?
These methods are related to the intrinsic lock (mutex) associated with an object,
not with threads directly. The Object class represents an intrinsic lock, and
threads use it for synchronization. Placing these methods in Object allows any
object to be used as a synchronization mechanism.
Q) Is it important to acquire the object lock before calling wait(), notify(), and
notifyAll()?
Yes, it is essential to acquire the object's lock before calling these methods.
Otherwise, IllegalMonitorStateException will be thrown. These methods manipulate
the thread's state regarding the lock associated with the object.
Q) What is the significance of yield() method, and what state does it put the
thread in?
The yield() method is used to give a hint to the scheduler that the current thread
is willing to yield its current use of the CPU. It puts the thread from running
state to the runnable state, allowing other threads to run. However, it doesn't
guarantee that the scheduler will switch to other threads.
wait():
Called on an object to release the lock and enter the waiting state.
Must be called from within a synchronized block.
Can be woken up by notify() or notifyAll().
sleep():
Difference:
yield() hints to the scheduler to give other threads a chance, but it doesn't
guarantee the switch.
sleep() pauses the execution of the current thread for a specified duration.
Similarities:
If you don't override the run() method in a thread, the default implementation in
the Thread class does nothing. The thread will start and terminate without
executing any custom logic.
Overriding the start() method in a thread is not recommended and may lead to
unpredictable behavior. The original start() method in the Thread class is
responsible for initializing and starting the new thread, including calling the
run() method. Changing this behavior may disrupt the proper initialization and
execution of the thread.
Thread starvation occurs when a thread is unable to gain regular access to shared
resources and is unable to make progress. It can happen due to unfair scheduling or
inefficient resource allocation.
A ThreadGroup in Java is a way to group multiple threads into a single unit. The
default priority of a newly created ThreadGroup is the same as the priority of the
thread that creates it. Important methods include setMaxPriority(), activeCount(),
enumerate(), and destroy().
Thread priorities are integer values assigned to threads in Java, indicating their
relative priority for execution. The priority range is from Thread.MIN_PRIORITY (1)
to Thread.MAX_PRIORITY (10). Higher priority threads are scheduled to run before
lower-priority threads, but it doesn't guarantee strict execution order.
Synchronized Block:
Byte Streams:
InputStream/OutputStream:
FileInputStream:
The File class in Java represents a file or directory path. Some methods of the
File class include:
java
Copy code
FileInputStream fileInput = new FileInputStream("input.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
DataInputStream dataInput = new DataInputStream(bufferedInput);
Here, DataInputStream is layered on top of BufferedInputStream, which is layered on
top of FileInputStream.
Q) What is RandomAccessFile?
BufferedInputStream:
DataInputStream:
Scanner:
java
Copy code
public static void main(String[] args) {
String name = null;
File file = new File("myfile.txt");
System.out.print(file.exists());
}
The output will be false if the file "myfile.txt" does not exist.
java
Copy code
public static void main(String[] args) {
String parent = null;
File file = new File(parent, "myfile.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
This code will create a new file named "myfile.txt" in the current working
directory.
Please note that handling IOException is essential for production code, and it's
not recommended to print the stack trace directly to the console in real-world
applications.
java
Copy code
FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));
The code may throw FileNotFoundException and IOException during the creation of a
FileOutputStream. Both exceptions should be handled or declared in the method
signature.
Serializable:
Serializable is a marker interface and does not contain any methods. Its purpose is
to indicate that the objects of the class can be serialized, allowing the default
serialization mechanism to be used.
Q) While serializing, you want some of the members not to serialize? How do you
achieve it?
You can use the transient keyword to indicate that certain members should not be
serialized. For example:
java
Copy code
private transient int nonSerializableField;
Q) What will happen if one of the members (contained object) in the class doesn't
implement the Serializable interface?
Q) If a class is Serializable but its superclass is not, what will be the state of
the instance variables inherited from the superclass after deserialization?
Q) Can you customize the Serialization process or can you override the default
Serialization process in Java?
Yes, serialized objects can be transferred over a network. The byte stream
representation of the serialized object can be sent and reconstructed at the
destination.
Static variables are not serialized during Java Serialization. They are associated
with the class rather than with an instance of the class.
The transient variable will be initialized to its default value (0, null, or false,
depending on its type) after deserialization.
Q) What is the use of serialVersionUID?
No, static variables are not saved as part of serialization. They are associated
with the class rather than with an instance, and their values are not serialized.
What is an exception?
What is Exception in Java?
What are the Exception Handling Keywords in Java?
Explain Java Exception Hierarchy?
What are important methods of Java Exception Class?
Explain Java 7 ARM Feature and multi-catch block?
What is difference between Checked and Unchecked Exception in Java?
What is difference between throw and throws keyword in Java?
How to write custom exception in Java?
What is OutOfMemoryError in Java?
What are different scenarios causing “Exception in thread main”?
What is difference between final, finally and finalize in Java?
What happens when exception is thrown by main method?
Can we have an empty catch block?
Provide some Java Exception Handling Best Practices?
Error: Represents serious errors that are beyond the control of the application,
such as OutOfMemoryError.
Example:
java
Copy code
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// Code to read from the file
} catch (IOException e) {
// Exception handling
}
Multi-catch block: Introduced in Java 7, it allows catching multiple exceptions in
a single catch block.
Example:
java
Copy code
try {
// Code that may throw multiple exceptions
} catch (IOException | SQLException e) {
// Common exception handling for IOException and SQLException
}
Q) What is the difference between Checked and Unchecked Exception in Java?
Checked Exceptions: These are exceptions that are checked at compile-time. The
compiler ensures that these exceptions are either caught or declared using the
throws clause. Examples include IOException, ClassNotFoundException, etc.
Unchecked Exceptions (RuntimeException): These are exceptions that are not checked
at compile-time. It is not mandatory to catch or declare them. Examples include
NullPointerException, ArrayIndexOutOfBoundsException, etc.
Example:
java
Copy code
throw new IllegalArgumentException("Invalid argument");
throws: Used in the method signature to declare that the method may throw one or
more exceptions. It specifies the types of exceptions that a method can throw.
Example:
java
Copy code
void myMethod() throws IOException, InterruptedException {
// Method code
}
Q) How to write a custom exception in Java?
To create a custom exception in Java, you need to extend the Exception class (or
one of its subclasses) or implement the Throwable interface. Example:
java
Copy code
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
Q) What is OutOfMemoryError in Java?
OutOfMemoryError is a subclass of Error and indicates that the Java Virtual Machine
(JVM) has run out of memory. This error is usually thrown when there is not enough
heap space to allocate a new object.
final: It is a keyword used to declare constants, make classes not extendable, and
prevent method overriding.
finally: It is a block used in exception handling. The code within the finally
block is guaranteed to be executed, whether an exception occurs or not.
Example:
java
Copy code
try {
// Code that may throw an exception
} finally {
// Code that will be executed regardless of an exception
}
finalize: It is a method in the Object class. It is called by the garbage collector
before reclaiming an object's memory. It is not recommended to rely on finalize for
resource cleanup.
If an unhandled exception is thrown by the main method, the program terminates, and
an error message containing information about the exception is printed to the
console.
Use specific exceptions: Catch specific exceptions rather than using a generic
catch block.
Handle exceptions appropriately: Choose between handling exceptions locally or
propagating them.
Log exceptions: Always log exceptions or at least print the stack trace to aid in
debugging.
Avoid empty catch blocks: Empty catch blocks make it challenging to diagnose and
fix issues.
Use try-with-resources: Utilize the try-with-resources statement for automatic
resource management.
Define custom exceptions: Create custom exceptions for application-specific error
conditions.
Avoid catching Exception or Throwable: Be specific about the exceptions you catch
to avoid unintended consequences.
Handle exceptions in the right layer: Handle exceptions at the appropriate layer of
your application.
Validate inputs: Validate inputs to prevent common runtime exceptions.
Consider exception chaining: Use exception chaining to preserve information about
the original exception.
What is the problem with below programs and how do we fix it?
How the exceptions are handled in java? OR Explain exception handling mechanism in
java?
What is the difference between error and exception in java?
Can we keep other statements in between try, catch and finally blocks?
Can we write only try block without catch and finally blocks?
What is unreachable catch block error
Explain the hierarchy of exceptions in java?
What are run time exceptions in java. Give example?
hat is OutOfMemoryError in java
what are checked and unchecked exceptions in java?
What is the difference between ClassNotFoundException and NoClassDefFoundError in
java?
Does finally block get executed If either try or catch blocks are returning the
control?
Can we throw an exception manually? If yes, how?
What is Re-throwing an exception in java?
What is the use of throws keyword in java?
You haven't provided any specific code. Please provide the code you want assistance
with, and I'll be happy to help identify and address any issues.
Q) How are exceptions handled in Java? OR Explain the exception handling mechanism
in Java?
In Java, exceptions are handled through a combination of the try, catch, finally,
and throw keywords.
Error: Represents serious issues that are typically beyond the control of the
application. Errors are often caused by external factors, and the application
usually cannot recover from them. Examples include OutOfMemoryError and
StackOverflowError.
Q) Can we keep other statements in between try, catch, and finally blocks?
Yes, you can have other statements between try, catch, and finally blocks.
Example:
java
Copy code
try {
// Code that may throw an exception
System.out.println("Inside try block");
} catch (Exception e) {
// Exception handling
System.out.println("Caught an exception");
} finally {
// Code in the finally block
System.out.println("Inside finally block");
}
Q) Can we write only the try block without catch and finally blocks?
Yes, it is valid to have only the try block without catch and finally blocks.
However, it is common to have either a catch block or a finally block (or both) to
handle exceptions or perform cleanup operations.
An "unreachable catch block" error occurs when a catch block is written for an
exception type that cannot be thrown by the corresponding try block. This can
happen if the catch block is for a checked exception that is not thrown by the try
block.
The hierarchy of exceptions in Java is based on the Throwable class. The main
branches are:
Error: Represents serious errors that are beyond the control of the application.
RuntimeException: Represents exceptions that can be caught during runtime and are
not mandatory to be caught or declared.
Runtime exceptions, also known as unchecked exceptions, are exceptions that occur
at runtime and are not required to be caught or declared. Examples include
NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
Example:
java
Copy code
public class Example {
public static void main(String[] args) {
int result = 5 / 0; // ArithmeticException: / by zero
}
}
Q) What is OutOfMemoryError in Java?
OutOfMemoryError is a subclass of Error and occurs when the Java Virtual Machine
(JVM) cannot allocate more memory for an object. It indicates that the application
has exhausted the available heap space.
NoClassDefFoundError: Occurs when the class was present during compilation but not
found during runtime. It indicates that the class was available during compilation
but is missing at runtime.
Q) Does the finally block get executed if either try or catch blocks are returning
control?
Yes, you can throw an exception manually using the throw keyword. You can throw an
instance of any class that is a subclass of Throwable.
Example:
java
Copy code
public class Example {
public static void main(String[] args) {
throw new RuntimeException("This is a manually thrown exception");
}
}
Q) What is Re-throwing an exception in Java?
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (Exception e) {
// Additional processing
throw e; // Re-throwing the caught exception
}
Q) What is the use of the throws keyword in Java?
The throws keyword is used in the method signature to declare that a method may
throw one or more exceptions. It informs the caller of the method about the
exceptions that need to be handled or propagated. The caller can choose to catch
the declared exceptions or use the throws clause to pass the responsibility to
higher levels.
Example:
java
Copy code
void myMethod() throws IOException, InterruptedException {
// Method code
}
What is the difference between final, finally and finalize in java?
How do you create customized exceptions in java
What is ClassCastException in java?
What is StackOverflowError in java?
What are chained exceptions in java?
Give some examples to checked exceptions?
What is the use of printStackTrace() method?
How does exception handling work in Java?
What are exception handling keywords in Java?
What is the purpose of the throw and throws keywords?
How can you handle an exception?
Explain the Java exception hierarchy.
How can you catch multiple exceptions?
What is the difference between checked and unchecked exceptions in Java?
What is the difference between throw and throws keyword in Java?
final: It is a keyword used to declare constants, make classes not extendable, and
prevent method overriding.
Example:
java
Copy code
final int MAX_VALUE = 100;
final class MyClass { /* Class code */ }
final void myMethod() { /* Method code */ }
finally: It is a block used in exception handling. The code within the finally
block is guaranteed to be executed, whether an exception is thrown or not.
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling
} finally {
// Code that will be executed regardless of an exception
}
finalize: It is a method in the Object class. It is called by the garbage collector
before reclaiming an object's memory. It is not recommended to rely on finalize for
resource cleanup.
Example:
java
Copy code
protected void finalize() throws Throwable {
// Code for finalization
}
Q) How do you create customized exceptions in Java?
To create a customized exception in Java, you need to extend the Exception class
(or one of its subclasses) or implement the Throwable interface.
Example:
java
Copy code
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
You can then throw and catch instances of this custom exception in your code.
Example:
java
Copy code
Object obj = "Hello";
Integer num = (Integer) obj; // ClassCastException
Q) What is StackOverflowError in Java?
StackOverflowError occurs when the call stack overflows due to excessive method
recursion. Each method call consumes a certain amount of stack space, and when the
stack is full, a StackOverflowError is thrown.
Example:
java
Copy code
public class Example {
public static void recursiveMethod() {
recursiveMethod();
}
Chained exceptions allow you to associate one exception with another. This is
useful when you want to provide more information about the cause of an exception.
You can use the initCause() method to set the cause of an exception.
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (IOException e) {
RuntimeException myException = new RuntimeException("Custom exception
message");
myException.initCause(e);
throw myException;
}
Q) Give some examples of checked exceptions?
IOException
ClassNotFoundException
SQLException
These exceptions must be either caught or declared using the throws clause.
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (Exception e) {
e.printStackTrace();
}
Q) How does exception handling work in Java?
In Java, exception handling is done using the try, catch, finally, throw, and
throws keywords. The try block encloses the code that may throw an exception, the
catch block catches and handles exceptions, and the finally block contains code
that is always executed, whether an exception is thrown or not.
try
catch
finally
throw
throws
These keywords are used to handle and propagate exceptions.
Example:
java
Copy code
throw new IllegalArgumentException("Invalid argument");
throws: It is used in the method signature to declare that a method may throw one
or more exceptions. It specifies the types of exceptions that a method can throw.
Example:
java
Copy code
void myMethod() throws IOException, InterruptedException {
// Method code
}
Q) How can you handle an exception?
Exceptions can be handled using the try-catch block. The try block contains the
code that may throw an exception, and the catch block catches and handles the
exception.
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling
}
Q) Explain the Java exception hierarchy.
The Java exception hierarchy is based on the Throwable class and has two main
branches:
Error: Represents serious errors that are beyond the control of the application.
RuntimeException: Represents exceptions that can be caught during runtime and are
not mandatory to be caught or declared.
Example:
java
Copy code
try {
// Code that may throw multiple exceptions
} catch (IOException | SQLException e) {
// Common exception handling for IOException and SQLException
}
Q) What is the difference between checked and unchecked exceptions in Java?
Example:
java
Copy code
throw new IllegalArgumentException("Invalid argument");
throws: Used in the method signature to declare that a method may throw one or more
exceptions. It specifies the types of exceptions that a method can throw.
Example:
java
Copy code
void myMethod() throws IOException, InterruptedException {
// Method code
}
What is the difference between an exception and error?
What is the OutOfMemoryError in Java?
What are chained exceptions in Java?
How do you write a custom exception in Java?
What is the difference between final, finally, and finalize in Java?
What happens when an exception is thrown by the main method?
What is a try-with-resources statement?
What is a stacktrace and how does it relate to an exception?
What are the advantages of Java exceptions?
Can you throw any exception inside a lambda expression’s body?
What are the rules that we need to follow when overriding a method that throws an
exception?
What are some of the exception handling best practices?
Exception: Exceptions are events that occur during the execution of a program that
disrupt the normal flow of instructions. Exceptions in Java are represented by
objects derived from the Throwable class. Exceptions can be caught and handled.
Error: Errors are abnormal conditions that occur at runtime and are typically not
recoverable. Errors are represented by objects of the Error class or its
subclasses. Errors often indicate serious problems that cannot be handled by the
application.
OutOfMemoryError is a runtime error that occurs when the Java Virtual Machine (JVM)
cannot allocate more memory for an object. It indicates that the application has
exhausted the available heap space. Common subtypes include
java.lang.OutOfMemoryError: Java heap space and java.lang.OutOfMemoryError: PermGen
space.
Q) What are chained exceptions in Java?
Chained exceptions allow you to associate one exception with another. This is
useful when you want to provide more information about the cause of an exception.
You can use the initCause() method to set the cause of an exception.
Example:
java
Copy code
try {
// Code that may throw an exception
} catch (IOException e) {
RuntimeException myException = new RuntimeException("Custom exception
message");
myException.initCause(e);
throw myException;
}
Q) How do you write a custom exception in Java?
To create a custom exception in Java, you need to extend the Exception class (or
one of its subclasses) or implement the Throwable interface.
Example:
java
Copy code
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
You can then throw and catch instances of this custom exception in your code.
final: It is a keyword used to declare constants, make classes not extendable, and
prevent method overriding.
finally: It is a block used in exception handling. The code within the finally
block is guaranteed to be executed, whether an exception is thrown or not.
If an unhandled exception is thrown by the main method, the program terminates, and
an error message containing information about the exception is printed to the
console.
java
Copy code
try (FileReader fr = new FileReader("example.txt");
BufferedReader br = new BufferedReader(fr)) {
// Code that uses FileReader and BufferedReader
} catch (IOException e) {
// Exception handling
}
Q) What is a stack trace, and how does it relate to an exception?
A stack trace is a list of method calls that shows the sequence of invocations that
led to the point where the exception occurred. It includes the names of the
methods, line numbers, and class names involved in the call stack. The stack trace
is printed when an exception is thrown, helping developers identify the source of
the error.
Lambda expressions can throw exceptions, but the exceptions must be compatible with
the functional interface's throws clause. If the functional interface does not
declare any checked exceptions, lambda expressions can throw unchecked exceptions.
Example:
java
Copy code
@FunctionalInterface
interface MyFunctionalInterface {
void myMethod() throws MyCustomException;
}
The overridden method can declare the same exception types as the parent method or
its subtypes.
The overridden method can declare fewer exception types (subtypes of the parent
exception types).
The overridden method cannot declare new or broader checked exception types in its
throws clause.
Q) What are some of the exception handling best practices?
Use Specific Exceptions: Catch specific exceptions rather than using a generic
catch block.
Log Exceptions: Always log exceptions or at least print the stack trace to aid in
debugging.
Avoid Empty Catch Blocks: Empty catch blocks make it challenging to diagnose and
fix issues.
Handle Exceptions at the Right Layer: Handle exceptions at the appropriate layer of
your application.
Use try-with-resources: Utilize the try-with-resources statement for automatic
resource management.
Define Custom Exceptions: Create custom exceptions for application-specific error
conditions.
Avoid Catching Exception or Throwable: Be specific about the exceptions you catch
to avoid unintended consequences.
Validate Inputs: Validate inputs to prevent common runtime exceptions.
Consider Exception Chaining: Use exception chaining to preserve information about
the original exception.
Use Checked Exceptions Wisely: Avoid excessive use of checked exceptions; prefer
unchecked exceptions for recoverable errors.
How garbage collector knows that the object is not in use and needs to be removed?
Can Java thread object invoke start method twice?
Give the list of Java Object class methods.
Can we call servlet destory() from service()?
Can we override static method?
Can you list serialization methods?
What is the difference between super() and this()?
How to prevent a method from being overridden?
Can we create abstract classes without any abstract methods?
How to destroy the session in servlets?
Can we have static methods in interface?
What is transient variable?
Incase, there is a return at the end of try block, will execute finally block?
What is abstract class or abstract method?
What is default value of a boolean?
When to use LinkedList or ArrayList?
What is daemon thread?
Does each thread in java uses seperate stack?
What is the difference between Enumeration and Iterator?
Find out switch statement output.
The garbage collector identifies objects that are no longer reachable by tracing
the object references. It starts from a set of root objects (such as local
variables, static variables, and active threads) and follows references to other
objects. Objects that cannot be reached from any root are considered unreachable
and are eligible for garbage collection. Java's garbage collector uses various
algorithms, such as the Mark-and-Sweep algorithm, to identify and reclaim memory
occupied by unreachable objects.
Q) Can a Java thread object invoke the start method twice?
No, a Java thread object cannot invoke the start method twice. Attempting to do so
will result in an IllegalThreadStateException. Once a thread has been started, it
cannot be started again. To restart a thread, you need to create a new thread
object.
Some of the commonly used methods from the Object class are:
toString()
equals(Object obj)
hashCode()
getClass()
notify()
notifyAll()
wait()
finalize()
Q) Can we call the destroy() method of a servlet from service()?
Yes, you can call the destroy() method of a servlet from the service() method.
However, it is not a common or recommended practice. The destroy() method is
typically called by the servlet container when it decides to unload the servlet.
Manually calling destroy() from service() may lead to unexpected behavior.
No, static methods in Java cannot be overridden. They are associated with the class
itself rather than with instances of the class. Inheritance and polymorphism do not
apply to static methods. If a subclass declares a static method with the same
signature as a static method in its superclass, it hides the superclass method
rather than overriding it.
In Java, the Serializable interface does not declare any methods. It is a marker
interface that indicates that a class can be serialized. However, the serialization
process involves two special methods that can be implemented in the serialized
class:
Example:
java
Copy code
super();
this(): It is used to invoke the constructor of the same class. It must also be the
first statement in the constructor if used.
Example:
java
Copy code
this();
Q) How to prevent a method from being overridden?
Example:
java
Copy code
public class MyClass {
public final void myFinalMethod() {
// Method implementation
}
}
Q) Can we create abstract classes without any abstract methods?
Yes, we can create abstract classes without any abstract methods. An abstract class
may have regular (non-abstract) methods, instance variables, and constructors. The
presence of at least one abstract method is not mandatory for a class to be
declared as abstract.
To destroy a session in servlets, you can use the invalidate() method provided by
the HttpSession interface. The invalidate() method removes all the attributes and
marks the session as invalid.
Example:
java
Copy code
HttpSession session = request.getSession();
session.invalidate();
Q) Can we have static methods in an interface?
Yes, starting from Java 8, interfaces can have static methods. These methods are
declared using the static keyword and can be called on the interface itself,
without creating an instance of the interface.
Example:
java
Copy code
public interface MyInterface {
static void myStaticMethod() {
// Static method implementation
}
}
Q) If there is a return at the end of the try block, will the finally block
execute?
Yes, the finally block will execute even if there is a return statement at the end
of the try block. The finally block is used for cleanup and is guaranteed to be
executed regardless of how the try block is exited (whether by normal completion,
an exception, or a return statement).
java
Copy code
public abstract class MyAbstractClass {
public abstract void myAbstractMethod();
java
Copy code
public abstract class MyAbstractClass {
public abstract void myAbstractMethod();
}
Q) What is the default value of a boolean?
ArrayList: Use ArrayList when you need fast random access to elements and the list
size does not change frequently. ArrayList is implemented as a dynamic array.
LinkedList: Use LinkedList when you need fast insertion and deletion of elements,
especially in the middle of the list. LinkedList is implemented as a doubly-linked
list.
A daemon thread in Java is a thread that runs in the background, providing services
to other threads. A daemon thread does not prevent the Java Virtual Machine (JVM)
from exiting when all non-daemon threads have completed their execution.
Example:
java
Copy code
Thread daemonThread = new Thread(() -> {
// Daemon thread code
});
daemonThread.setDaemon(true);
daemonThread.start();
Q) Does each thread in Java use a separate stack?
Yes, each thread in Java has its own separate stack. The stack is used to store
local variables, method call information, and partial results. Having a separate
stack for each thread allows threads to have independent execution paths and
prevents interference between threads.
Enumeration can be used to traverse elements in legacy collections like Vector and
Hashtable.
Iterator is a more universal interface that can be used with any collection
implementing the Iterable interface.
Iterator has additional methods like remove(), and it supports the foreach loop
introduced in Java 5.
Q) Find out the switch statement output.
To provide the output for a switch statement, I would need the specific switch
statement code or scenario. If you have a particular switch statement in mind,
please provide the code, and I can explain the expected output.
No, the finally block will not be executed if System.exit() is called within a try
block. The System.exit() method terminates the Java Virtual Machine (JVM) and does
not allow further execution of the program, bypassing the finally block. If there
is a need for cleanup or finalization, it's better to handle it outside the try
block or before calling System.exit().
In Java, true and false are literals representing the boolean values true and
false. They are not keywords, but rather reserved words in the language.
URL Rewriting: Session information is encoded in URLs and passed between pages.
Hidden Form Fields: Session information is stored in HTML forms as hidden fields.
In Java, the ResultSet interface is used to retrieve and manipulate data from a
database. There are three types of ResultSet:
TYPE_FORWARD_ONLY: The default type. It allows traversal of the result set in the
forward direction only.
wait: The wait method is a method of the Object class and is used for inter-thread
communication. It is used in conjunction with notify and notifyAll methods to
coordinate the execution of multiple threads.
sleep: The sleep method is a static method of the Thread class and is used to pause
the execution of the current thread for a specified duration. It does not release
the monitor lock.
Q) What is ServletContext?
ServletContext is an interface in Java Servlet API that represents the entire web
application and provides a mechanism for communication between servlets. It allows
servlets to share information, such as attributes, across the entire application.
The ServletContext is created by the web container at the time of deploying the web
application.
Q) What happens if one of the members in a class does not implement the
Serializable interface?
If one of the members (instance variables) in a class does not implement the
Serializable interface, and an attempt is made to serialize an object of that
class, a NotSerializableException will be thrown. All members of a class, including
those inherited from superclasses, need to implement Serializable for the entire
object to be serializable.
A race condition occurs in a concurrent program when the behavior of the program
depends on the relative timing of events, such as the order in which threads are
scheduled to run. It can lead to unpredictable and unintended results, as multiple
threads may access shared resources concurrently, resulting in unexpected
interactions.
Example:
java
Copy code
long currentTimeMillis = System.currentTimeMillis();
Q) How can you convert Map to List?
You can convert a Map to a List by using the ArrayList constructor that takes a
Collection as an argument. You can pass the Map's values() or entrySet() to create
a list of values or entries.
Example:
java
Copy code
Map<String, Integer> map = new HashMap<>();
// Populate the map
java
Copy code
ServletOutputStream outputStream = response.getOutputStream();
PrintWriter: It is used to send character data to the client. It is obtained from
the HttpServletResponse object.
Example:
java
Copy code
PrintWriter writer = response.getWriter();
Q) What is Java static import?
Java static import is a feature introduced in Java 5 that allows static members
(fields and methods) of a class to be imported directly into another class without
specifying the class name. It simplifies the code by avoiding the need to qualify
static members with the class name.
Example:
java
Copy code
import static java.lang.Math.*;
Use String when the content is fixed and will not change frequently. String objects
are immutable, meaning their values cannot be modified after creation.
Example:
java
Copy code
String str = "Hello";
Use StringBuffer when the content is expected to change frequently. StringBuffer is
mutable and allows efficient modifications.
Example:
java
Copy code
StringBuffer buffer = new StringBuffer("Hello");
buffer.append(" World");
Q) What is the difference between StringBuffer and StringBuilder?
A wrapper class in Java is a class that provides a way to use primitive data types
(such as int, char, boolean, etc.) as objects. Each primitive data type has a
corresponding wrapper class in Java. Wrapper classes are part of the Java API and
are used in situations where objects are required, such as in collections and when
working with Java generics.
Example:
java
Copy code
Integer intObj = new Integer(42); // Wrapper class for int
Character charObj = new Character('A'); // Wrapper class for char
The commonly used wrapper classes are Integer, Double, Boolean, etc.
Is Iterator a Class?
What is java classpath?
Can a class in java be private?
Is null a keyword in java?
What is the initial state of a thread when it is started?
What is the super class for Exception and Error?
What is Class.forName()?
Can interface be final?
What is the difference between exception and error?
What is default value of a local variables?
What is local class in java?
Can we initialise uninitialized final variable?
Can we declare abstract method as final?
Can we have finally block without catch block?
What is pass by value and pass by reference?
Can we declare main method as private?
What is the difference between preemptive scheduling and time slicing?
Can non-static member classes (Local classes) have static members?
What are the environment variables do we neet to set to run Java?
Can you serialize static fields of a class?
The Java Classpath is a parameter that tells the Java Virtual Machine (JVM) or Java
compiler where to find user-defined classes and packages. It is a sequence of
directories, JAR files, and ZIP archives that Java uses to search for classes when
executing a program. Classpath can be set using the -classpath or -cp option while
compiling or running Java programs.
Example:
bash
Copy code
java -cp directory1:directory2:myJar.jar MyClass
Q) Can a class in Java be private?
No, a top-level class in Java cannot be declared as private. The access modifiers
applicable to top-level classes are public, default (package-private), and
abstract. Inner classes, on the other hand, can be declared as private.
When a thread is started in Java, its initial state is "runnable." The start()
method is called on a thread to begin its execution, and the thread scheduler
determines when it will actually start running. Once started, the thread goes
through various states, including "running," "blocked," and "terminated."
The superclass for both Exception and Error in Java is Throwable. All exceptions
and errors in Java are subclasses of the Throwable class. The Throwable class
provides methods like getMessage() and printStackTrace() that are common to both
exceptions and errors.
Q) What is Class.forName()?
Example:
java
Copy code
try {
Class<?> myClass = Class.forName("com.example.MyClass");
// Perform operations with the loaded class
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Q) Can an interface be final?
No, an interface in Java cannot be declared as final. The final keyword is not
applicable to interfaces. Interfaces are meant to be implemented by classes, and
their methods are meant to be overridden by implementing classes. Making an
interface final would contradict the concept of providing a contract for
implementation.
An exception is a condition that occurs at runtime and disrupts the normal flow of
a program. Exceptions are typically recoverable, and they are represented by
classes derived from Exception.
Local variables in Java do not have default values. They must be explicitly
initialized before they are used. Attempting to use an uninitialized local variable
will result in a compilation error.
A local class in Java is a class that is defined within a block of code, such as a
method or a constructor. Local classes have access to the members of the enclosing
class and can also access local variables declared within the same block.
Example:
java
Copy code
public class MyClass {
public void myMethod() {
class LocalClass {
// Local class definition
}
// Code using local class
}
}
Q) Can we initialize uninitialized final variable?
A final variable in Java must be initialized exactly once, either at the time of
declaration or in the constructor. Once initialized, the value of a final variable
cannot be changed. If a final variable is uninitialized and an attempt is made to
use it without initialization, it will result in a compilation error.
No, it is not possible to declare an abstract method as final in Java. The final
keyword is used to indicate that a method cannot be overridden in subclasses.
However, since abstract methods are meant to be overridden by subclasses, declaring
them as final would be contradictory.
In Java, the terms "pass by value" and "pass by reference" refer to how arguments
are passed to methods:
Pass by Value: In Java, primitive data types (int, float, char, etc.) are passed by
value. This means that a copy of the actual value is passed to the method. Changes
made to the parameter inside the method do not affect the original value.
Example:
java
Copy code
void modifyValue(int x) {
x = 10; // Changes to x do not affect the original value
}
Pass by Reference: In Java, objects (instances of classes) are passed by value.
However, what is passed by value is the reference to the object, not the object
itself. Changes made to the object's state inside the method will affect the
original object.
Example:
java
Copy code
void modifyObject(StringBuilder str) {
str.append(" World"); // Changes to the object's state affect the original
object
}
Q) Can we declare the main method as private?
No, the main method in Java cannot be declared as private. The main method is the
entry point of a Java program, and it must be declared as public, static, and void.
It is the method that the Java Virtual Machine (JVM) looks for when starting the
execution of a Java program.
Time Slicing: Time slicing is a technique used in multitasking systems where each
task is assigned a fixed time slot (time quantum) during which it can execute.
After the time quantum expires, the task is preempted, and the CPU is given to the
next task in the queue.
No, non-static member classes (also known as inner classes) in Java cannot declare
static members. Inner classes have an implicit reference to an instance of the
outer class, and they are associated with an instance rather than the class itself.
Static members belong to the class, not to instances, so they are not allowed in
non-static member classes.
To run Java programs, the PATH environment variable should include the path to the
bin directory of the Java Development Kit (JDK). Additionally, the JAVA_HOME
environment variable should be set to the installation directory of the JDK.
Example:
bash
Copy code
export PATH=$PATH:/path/to/jdk/bin
export JAVA_HOME=/path/to/jdk
Q) Can you serialize static fields of a class?
Yes, static fields of a class can be serialized, but they are not part of the
serialized form of an object. When an object is serialized, only the instance
variables (non-static fields) are serialized. Static fields belong to the class
itself, and their values are associated with the class, not with individual object
instances. When deserializing an object, the static fields will have their default
values in the new instance.
Declaration: It involves specifying the data type and the name of the variable
without initializing its value. It informs the compiler that a variable with a
specific name and data type will be used in the program.
Example:
java
Copy code
int x; // Declaration of variable 'x'
Definition: It involves both declaring the variable and allocating memory for it.
The variable is given a specific memory location where its data can be stored.
Example:
java
Copy code
int x; // Declaration
x = 10; // Definition and initialization
In many cases, declaration and definition occur simultaneously in Java.
Serialization in Java is used to convert an object into a byte stream, which can be
easily saved to a file, sent over a network, or stored in a database.
Deserialization is the process of reconstructing the object from the byte stream.
Serialization is commonly used in scenarios like:
In an interface in Java, methods are implicitly public and abstract. The only
modifiers allowed for methods in an interface are:
public: Access specifier indicating that the method is accessible from any class.
abstract: Indicates that the method does not have a body and must be implemented by
the implementing class.
Starting from Java 8, interfaces can have default and static methods, which allow
for method implementation within the interface itself.
Runtime Class: The Runtime class in Java provides access to the Java runtime
environment. It allows the application to interface with the environment in which
the application is running. It includes methods for managing the execution
environment, executing processes, obtaining information about memory usage, and
more.
System Class: The System class in Java provides access to system resources and
standard input/output streams. It contains fields and methods for interacting with
the system, such as out for standard output, in for standard input, and err for
standard error. It also includes utility methods for managing properties, getting
the current time, and copying array elements.
ArrayList is generally faster than Vector in Java. The key differences are:
Synchronization: Vector is synchronized, meaning that all its methods are thread-
safe, which introduces a performance overhead. ArrayList is not synchronized by
default, making it faster in a single-threaded environment.
Growth Factor: Vector has a doubling growth factor, which means its capacity
doubles when it reaches its limit. ArrayList uses a 50% increment, making it more
memory-efficient when resizing.
java
Copy code
public class MyClass {
public static synchronized void staticSyncMethod() {
// Method code
}
}
synchronized Method: When a non-static method is declared as synchronized, it means
that the method is synchronized at the instance level. It uses the instance's
monitor (associated with the object) to control access. Only one thread can execute
any synchronized method of the object at a time.
Example:
java
Copy code
public class MyClass {
public synchronized void syncMethod() {
// Method code
}
}
Q) What is the order of catch blocks when catching more than one exception?
In Java, when catching multiple exceptions in a try-catch block, the order of catch
blocks matters. The catch blocks must be ordered from most specific to least
specific. If catch blocks are ordered in the opposite way, with the more general
exception types first, it will result in a compilation error.
Example:
java
Copy code
try {
// Code that may throw exceptions
} catch (IOException e) {
// Handle IOException
} catch (Exception e) {
// Handle more general exceptions
}
In this example, if the catch blocks were reversed, it would lead to a compilation
error.
Q) What is the difference between the prefix and postfix forms of the increment (+
+) operator?
Prefix (++i): Increments the value of i before its value is used in an expression.
Example:
java
Copy code
int i = 5;
int result = ++i; // i is incremented to 6 before being assigned to result
Postfix (i++): Increments the value of i after its current value is used in an
expression.
Example:
java
Copy code
int i = 5;
int result = i++; // i is assigned to result first, then incremented to 6
Q) What is hashCode?
hashCode is a method in Java that is used to get the hash code value of an object.
It returns a 32-bit signed integer that represents the hash code of the object. The
hash code is commonly used in hash-based data structures like hash tables to
quickly locate a data record given its search key.
Example:
java
Copy code
public class MyClass {
private int id;
@Override
public int hashCode() {
return id; // A simple hash code implementation using the id field
}
}
Q) What is the difference between Hashtable and HashMap?
Null Values: HashMap allows null values for both keys and values. Hashtable does
not allow null for either keys or values.
When overriding a method in Java, there are certain rules and restrictions to
follow:
The method in the subclass must have the same method signature (name, return type,
and parameters) as the method in the superclass.
The access level of the overriding method in the subclass cannot be more
restrictive than the access level of the overridden method in the superclass.
The overriding method cannot throw a broader range of exceptions than the
overridden method. It can throw the same exceptions or their subtypes.
The overriding method cannot be marked as static or final.
Q) What is the use of assert keyword?
The assert keyword in Java is used for testing purposes and is typically used to
check assumptions made by the programmer. It is a debugging aid that can be enabled
or disabled at runtime. If an assert statement evaluates to false during program
execution, an AssertionError is thrown.
Example:
java
Copy code
int value = -5;
assert value >= 0 : "Value must be non-negative"; // Assertion check
To enable assertions during program execution, the -ea (enable assertions) option
is used when running the Java Virtual Machine (JVM).
Example:
java
Copy code
// Adapter class for ActionListener interface
public class MyActionAdapter implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Default implementation, can be overridden in subclasses
}
}
Q) What is the difference between break, continue, and return statements?
continue: It is used to skip the rest of the code inside a loop for the current
iteration and proceed to the next iteration of the loop.
return: It is used to exit a method and return a value (if the method has a non-
void return type). It also terminates the execution of the current block of code.
These statements serve different purposes and are used in different contexts within
a program.
while Statement: The while loop in Java is a pre-test loop, meaning the condition
is checked before entering the loop. If the condition is false initially, the loop
will not be executed at all.
Example:
java
Copy code
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
do-while Statement: The do-while loop is a post-test loop, meaning the condition is
checked after the loop body is executed. This ensures that the loop body is
executed at least once, even if the condition is false initially.
Example:
java
Copy code
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
The primary difference is in when the loop condition is checked: before the loop
body (while) or after the loop body (do-while).
Memory Management:
C++: Uses try, catch, throw, and finally for exception handling.
Java: Uses try, catch, throw, and finally with a more structured approach to
exception handling.
Operator Overloading:
Access Control: Packages enable access control by using access modifiers (e.g.,
public, private) at the package level.
Example:
java
Copy code
try {
Class<?> dynamicClass = Class.forName("com.example.DynamicClass");
// Use dynamicClass to create instances or invoke methods dynamically
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Dynamic class loading is often used in scenarios where the classes to be loaded are
determined at runtime, such as when implementing plugins or extensions.
If you do not provide any constructors in a Java class, the compiler automatically
generates a default constructor for you. The default constructor is a no-argument
constructor with an empty body. This default constructor is implicitly present even
if you do not explicitly define any constructors in your class.
Example:
java
Copy code
public class MyClass {
// Compiler-generated default constructor
public MyClass() {
// Empty constructor body
}
}
If you provide any explicit constructor (with or without arguments), the compiler
does not generate the default constructor.
Shallow Cloning: Shallow cloning creates a new object and copies the contents of
the original object's fields to the new object. If the fields of the original
object include references to other objects, the references are copied, but the
referenced objects are not cloned. Both the original and cloned objects share
references to the same objects.
Deep Cloning: Deep cloning creates a new object and recursively clones all the
objects referenced by the original object. It creates copies of all the objects in
the object graph. As a result, the original and cloned objects are entirely
independent, and changes to one do not affect the other.
Example:
java
Copy code
// Shallow cloning using clone() method
MyObject clone = (MyObject) original.clone();
Yes, starting from Java 8, interfaces in Java can have methods with default
implementations and static methods. An interface with no abstract methods is known
as a "marker interface." Marker interfaces are used to indicate the capability or
property of a class without providing any specific method contracts.
Example:
java
Copy code
// Marker interface with no defined methods
public interface MarkerInterface {
}
java
Copy code
String str1 = new String("hello");
String str2 = new String("hello");
boolean result = (str1 == str2); // false (different objects in memory)
equals() Method: It is used for content or value comparison. The equals() method is
typically overridden in classes to provide a meaningful comparison based on the
content of objects.
Example:
java
Copy code
String str1 = new String("hello");
String str2 = new String("hello");
boolean result = str1.equals(str2); // true (same content)
The behavior of equals() depends on the implementation in the class. For some
classes (e.g., String), equals() is overridden to compare content.
Make the class final: This prevents the class from being extended.
Make fields private and final: This ensures that the fields cannot be modified once
initialized.
Provide no setter methods: Do not provide methods that modify the state of the
object.
Initialize fields in the constructor: Set the values of fields in the constructor
and do not provide any methods to change these values.
Do not expose mutable objects: If the class contains references to mutable objects,
make sure not to expose them directly. Return defensive copies instead.
Example:
java
Copy code
public final class ImmutableClass {
private final int intValue;
private final String stringValue;
protected: The member is accessible within its own package and by subclasses.
default (no modifier): The member is accessible only within its own package.
Access modifiers are used to implement encapsulation and control the level of
access to the members of a class.
Creating a class with only static utility methods (no instances needed).
Implementing a singleton pattern, where only one instance of the class is allowed.
Example:
java
Copy code
public class MyClass {
private MyClass() {
// Private constructor
}
Generics in Java provide a way to create classes, interfaces, and methods that
operate on different types without sacrificing type safety. Generics offer the
following benefits:
Type Safety: Generics enable compile-time type checking, reducing the chances of
runtime errors.
Code Reusability: Generics allow the creation of generic algorithms and data
structures that can work with different types.
Elimination of Type Casting: Generics eliminate the need for explicit type casting
as the type information is preserved.
Cleaner Code: Generics result in cleaner and more readable code by expressing the
intent of the code in a generic manner.
Example:
java
Copy code
// Without generics
List list = new ArrayList();
list.add("Hello");
String value = (String) list.get(0); // Explicit type casting
// With generics
List<String> genericList = new ArrayList<>();
genericList.add("Hello");
String genericValue = genericList.get(0); // No explicit type casting needed
Q) What is the difference between a product and a project?
Project: A project is a temporary endeavor with a specific goal and defined scope.
It is a set of activities and tasks undertaken to create a unique product, service,
or result. Projects are characterized by a defined beginning and end, and they
involve the coordination of resources (time, cost, personnel) to achieve the
project objectives.
In summary, a product is the end result, while a project is the process or series
of activities undertaken to create that result.
The substring() method in Java is used to extract a portion of a string. It has two
overloaded forms:
Example:
java
Copy code
String original = "Hello, World";
String substring1 = original.substring(7); // "World"
String substring2 = original.substring(0, 5); // "Hello"
The substring() method does not modify the original string; it creates a new string
with the specified substring. The indices provided should be within the bounds of
the string, or an IndexOutOfBoundsException will be thrown.
Java Library: A library in Java is a collection of classes and methods that provide
reusable functionality to developers. Libraries are typically a set of pre-written
code that can be used for common tasks. Developers use libraries by including them
in their projects and calling the provided functions.
Example: Apache Commons Lang library provides utility classes for common operations
like string manipulation, array manipulation, etc.