JAVA New
JAVA New
Inheritance
Encapsulation
Polymorphism
Data Abstraction
Single inheritance
Multiple inheritance
Multiple inheritance comes into picture Multilevel inheritance means a class inherits
when a class inherits more than one base from another class which itself is a subclass
class of some other base class
Increases the time and effort required to execute a program as it requires jumping
back and forth between different classes
The parent class and the child class get tightly coupled
Any modifications to the program would require changes both in the parent as well
as the child class
Needs careful implementation else would lead to incorrect results
What is polymorphism?
What is encapsulation?
Encapsulation refers to binding the data and the code that works on that together
in a single unit. For example, a class. Encapsulation also allows data-hiding as the
data specified in one class is hidden from other classes.
Abstract class
Abstract method
Allows showing important aspects while Binds code and data together into a single
hiding implementation details unit and hides it from the world
A try/ catch block is used to handle exceptions. The try block defines a set of
statements that may lead to an error. The catch block basically catches the
exception.
A finally block consists of code that is used to execute important code such as
closing a connection, etc. This block executes when the try block exits. It also makes
sure that finally block executes even in case some unexpected exception is
encountered.
@Override
public final String drive() {
return "Driving an electric car";
}
class Demo{
public Demo(int i){
System.out.println("int");
}
a) int
b) short
c) Compile-time error
d) Run-time error
Answer:
a) int
Exception Handling
How are exceptions handled in Java?
1. try-catch block: The try section holds the code that needs to be normally executed and it
monitors for any possible exception that could occur. The catch block “catches” the
exception thrown by the try block. It could consist of logic to handle failure scenario or
the catch block could simply rethrow the exception by using the “throw” keyword.
2. finally block: Regardless of whether an exception has occurred or not, if we need to
execute any logic, then we place it in the final block that is usually associated with the
try-catch block or just with the try block. The final block is not executed
when System.exit(0) is present in either the try or catch block.
Exception propagation is a process where the compiler makes sure that the exception is
handled if it is not handled where it occurs. If an exception is not caught where it occurred,
then the exception goes down the call stack of the preceding method and if it is still not caught
there, the exception propagates further down to the previous method. If the exception is not
handled anywhere in between, the process continues until the exception reaches the bottom of
the call stack. If the exception is still not handled in the last method, i.e, the main method, then
the program gets terminated.
Runtime exceptions are those exceptions that occur at the run time of the program execution.
These exceptions are not noticed by the compiler at the compile time and hence the program
successfully gets compiled. Therefore, they are also called unchecked exceptions. All
subclasses of the java.lang.RunTimeException class and java.lang.Error class belongs to runtime
exceptions. Examples of runtime exceptions include NullPointerException,
NumberFormatException, ArrayIndexOutOfBoundException, StackOverflowError,
ClassCastException, ArithmeticException, ConcurrentModificationException, etc.
7. What is the difference between the throw and throws keywords in Java?
The throw keyword allows a programmer to throw an exception object to interrupt normal
program flow. The exception object is handed over to the runtime to handle it. For example, if
we want to signify the status of a task is outdated, we can create an OutdatedTaskException that
extends the Exception class and we can throw this exception object as shown below:
Since Exception is the base class for all exception types, make use of a catch block that
catches the Exception class-
try {
// do something
} catch (Exception exception) {
// handle exception
}
However, it is recommended to use accurate Exception handlers instead of generic ones. This
is because having broad exception handlers could make the code error-prone by catching
exceptions that were not anticipated in the software design and could result in unexpected
behavior.
From Java 7 onwards, it is now possible to implement multiple catch blocks as shown
below -
try {
// do something
} catch (FileNotFoundException fileNotFoundException) {
// handle FileNotFoundException
} catch (EOFException eofException) {
// handle EOFException
}
When we are using multiple catch blocks, we need to ensure that in a case where the
exceptions have an inheritance relationship, the child exception type should be the first and the
parent type later to avoid a compilation error.
Java 7 also began to provide the usage of multi-catch blocks for reducing duplication of
code if the exception handling logic was similar for different exception types. The syntax
of the multi-catch block is as shown below-
try {
// ...
} catch (FileNotFoundException | EOFException exception) {
// ...
}
What is the difference between ClassNotFoundException and
NoClassDefFoundError?
Both these exceptions occur when ClassLoader or JVM is not able to find classes while
loading during run-time. However, the difference between these 2 are:
ClassNotFoundException: This exception occurs when we try to load a class that is not
found in the classpath at runtime by making use of
the loadClass() or Class.forName() methods.
NoClassDefFoundError: This exception occurs when a class was present at compile-
time but was not found at runtime
Experienced
Exceptions in Java are hierarchical and follow inheritance to categorize different kinds of
exceptions. The parent class of all exceptions and errors is Throwable. This class has 2 child
classes - Error and Exception.
1. Errors are those abnormal failures that are not in the scope of recovery for the
application. It is not possible to anticipate errors or recover from them. Errors could be
due to failures in hardware, out-of-memory, JVM crash, etc.
2. Exception is divided into 2 categories - Checked Exception and Unchecked Exception.
Checked Exceptions are those that can be anticipated in the program at the time of
compilation and we should try to handle this otherwise it leads to a compilation
error. IllegalAccessException, ClassNotFoundException, and
FileNotFoundException are some of the types of checked exceptions. Exception
is the parent class of all checked exceptions.
Unchecked exceptions are those exceptions that occur during runtime and are not
possible to identify at the time of compilation. These exceptions are caused due to
mistakes in application programming - for example, we try to access an element
from an array index that is out of bounds from the length of the array, while trying
to run operations on null objects and so on. RuntimeException,
ArrayIndexOutOfBoundException, NullPointerException, ClassCastException,
NumberFormatException, IllegalArgumentException, etc are some of the types of
unchecked exceptions. The parent class of all runtime/unchecked exceptions is
RuntimeException.
When there is an exception thrown by the main() method if the exception is not handled, then
the program is terminated by the Java Runtime, and the exception message along with the stack
trace is printed in the system console.
Is it possible to throw checked exceptions from a static block?
We cannot throw a check exception from a static block. However, we can have try-catch logic
that handles the exception within the scope of that static block without rethrowing the
exception using the throw keyword. The exceptions cannot be propagated from static blocks
because static blocks are invoked at the compiled time only once and no method invokes these
blocks
Why it is always recommended to keep the clean-up activities like closing the
I/O resources or DB connections inside a finally block?
When there is no explicit logic to terminate the system by using System.exit(0), finally block is
always executed irrespective of whether the exception has occurred or not. By keeping these
cleanup operations in the finally block, it is always ensured that the operations are executed
and the resources are closed accordingly. However, to avoid exceptions in the finally block, we
need to add a proper validation check for the existence of the resource and then attempt to
clean up the resources accordingly
Are we allowed to use only try blocks without a catch and finally blocks?
Before Java 7, we were not allowed to use only try blocks. The try block should have been
followed by a catch or a finally block. But from Java 7 onwards, we can simply have a try
block with a catch or finally blocks in the form of try-with-resources that takes parameters
implementing the AutoCloseable interface. Note that, if the parameters do not implement
the AutoCloseable interface, then it leads to an error
If we are using a standard functional interface that is given by Java, then we can throw
only unchecked exceptions. This is because the standard functional interfaces of Java do
not have a “throws” clause defined in their signature. For example, we can
throw IllegalArgumentException inside a function interface as shown below:
If we are using custom functional interfaces, then we can throw checked as well as
unchecked exceptions. Custom functional interfaces can be defined by using
the @FunctionalInterface keyword.
Collections
2. What are Collection related features in Java 8?
Java 8 has brought major changes in the Collection API. Some of the changes
are:
1. Java Stream API for collection classes for supporting sequential as well as
parallel processing
2. Iterable interface is extended with forEach() default method that we can
use to iterate over a collection. It is very helpful when used with lambda
expressions because its argument Consumer is a function interface.
3. Miscellaneous Collection API improvements such
as forEachRemaining(Consumer action) method in Iterator interface,
Map replaceAll(), compute(), merge() methods.
What is IdentityHashMap?
The IdentityHashMap implements the Map interface using Hashtable, comparing keys
(and values) using reference equality instead of object equality. This class implements
the Map interface, but it intentionally breaks Map’s general contract, which demands
that objects are compared using the equals() method. This class is used when the user
allows objects to be compared using references. It belongs to java.util package.
import java.util.*;
list_1.add("Geeks");
list_1.add("For");
list_1.add("ForGeeks");
list_2.add("GeeksForGeeks");
list_2.add("A computer portal");
Output
ArrayList 1: [Geeks, For, ForGeeks]
ArrayList 2: [GeeksForGeeks, A computer portal]
Joined ArrayLists: [Geeks, For, ForGeeks, GeeksForGeeks, A computer
portal]
What will happen if two different keys of HashMap return the same
hashcode()?
When two different keys of HashMap return the same hash code, they will end up in the
same bucket; therefore, collisions will occur. n case of collision, i.e. index of two or
more nodes is the same, nodes are joined by a link list i.e. the second node is referenced
by the first node and the third by the second, and so on.
Collection Collections
java.util.Collection is an interface java.util.Collections is a class
Is used to represent a group of objects It is used to define various utility method
as a single entity for collection objects
It is the root interface of the Collection
It is a utility class
framework
It is used to derive the data structures of It contains various static methods which
the Collection framework help in data structure manipulation
List Map
Belongs to java.util package Belongs to java.util package
Extends the Collection interface Doesn’t extend the Collection interface
Duplicate keys are not allowed but
Duplicate elements are allowed
duplicate values are
Only one null key can be stored but
Multiple null values can be stored
multiple null values are allowed
Preserves the insertion order Doesn’t maintain any insertion order
Stores elements based on Array Data Stores data in key-value pairs using
Structure various hashing techniques
Differentiate between HashMap and TreeMap.
HashMap TreeMap
Doesn’t preserves any ordering Preserves the natural ordering
Implicitly implements the hashing Implicitly implements the Red-Black Tree
principle Implementation
Can store only one null key Cannot store any null key
More memory usage Less memory usage
Not synchronized Not synchronized
Fail-Fast Fail-Safe
These types of iterators do not allow
These types of iterators allow modifying
modifying the collection while iterating
the collection while iterating over it.
over it.
It throws
ConcurrentModificationException if the No exception is thrown if the collection is
collection is modified while iterating modified while iterating over it.
over it.
It uses the original collection while It uses a copy of the original collection
traversing the elements. while traversing over it.
No extra memory is required in this
Extra memory is required in this case.
case.
JUNIT
Top 50 JUnit Interview Questions and Answers for 2023 (knowledgehut.com)
2. Write test cases: You should write JUnit test cases that test the
interactions between the identified components. These tests should
simulate real-world scenarios that test the integration between the
components.
6. Run the tests: You can run your JUnit tests using a build tool like Maven
or Gradle. This will automatically execute the tests and generate reports
that indicate whether the tests passed or failed.
By following these steps, you can perform comprehensive integration testing using
JUnit, which can help ensure that your system components work together correctly
and prevent bugs from being introduced into the production environment.
GIT
Git commit - Commit changes to head but not to the remote repository
The Git push command is used to push the content in a local repository to a remote repository.
After a local repository has been modified, a push is executed to share the modifications with
remote team members.
A Git merge conflict is an event that occurs when Git is unable to resolve the differences in code
between the two commits automatically.
Git is capable of automatically merging the changes only if the commits are on different lines or
branches.
Here are the steps that will help you resolve conflicts in Git:
The last step is to commit the changes in the file with the help of the git commit
command.
What is the functionality of git clean command?
The git clean command removes the untracked files from the working directory.
Git stash is a powerful tool that allows you to save your changes and revert your working
directory to a previous state. This is especially useful when switching branches or reverting to a
previous commit.
And Git Stash takes a snapshot of your changes and stores them away for later use.
AGILE
Top 40+ Agile Scrum Interview Questions 2023 (whizlabs.com)