0% found this document useful (0 votes)
28 views

JAVA New

Uploaded by

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

JAVA New

Uploaded by

akumar181092
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

OOPS Concepts

What is the difference between OOP and SOP?

Object-Oriented Programming Structural Programming


Object-Oriented Programming is a type
of programming which is based on Provides logical structure to a program
objects rather than just functions and where programs are divided functions
procedures
Bottom-up approach Top-down approach
Provides data hiding Does not provide data hiding
Can solve problems of any complexity Can solve moderate problems
Code can be reused thereby reducing
Does not support code reusability
redundancy

4. What are the main features of OOPs?

 Inheritance
 Encapsulation
 Polymorphism
 Data Abstraction

What are the different types of inheritance?

 Single inheritance
 Multiple inheritance

What is the difference between multiple and multilevel inheritance?


Multiple Inheritance Multilevel 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

Example: A class describing a sports car will


Example: A class defining a child inherits
inherit from a base class Car which inturn
from two base classes Mother and Father
inherits another class Vehicle
What are the limitations of inheritance?

 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?

 Polymorphism refers to the ability to exist in multiple forms. Multiple


definitions can be given to a single interface. For example, if you have a class
named Vehicle, it can have a method named speed but you cannot define it
because different vehicles have different speed. This method will be defined
in the subclasses with different definitions for different vehicles.

What is static polymorphism?


Static polymorphism (static binding) is a kind of polymorphism that occurs at
compile time. An example of compile-time polymorphism is method overloading.

20. What is dynamic polymorphism?


Runtime polymorphism or dynamic polymorphism (dynamic binding) is a type of
polymorphism which is resolved during runtime. An example of runtime
polymorphism is method overriding.

Differentiate between overloading and overriding.


Overloading Overriding

Child class redefining methods present in


Two or more methods having the same
the base class with the same parameters/
name but different parameters or signature
signature

Resolved during compile-time Resolved during runtime

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.

What is data abstraction?


Data abstraction is a very important feature of OOPs that allows displaying only the
important information and hiding the implementation details. For example, while
riding a bike, you know that if you raise the accelerator, the speed will increase, but
you don’t know how it actually happens. This is data abstraction as the
implementation details are hidden from the rider.

29. How to achieve data abstraction?


Data abstraction can be achieved through:

 Abstract class
 Abstract method

30. What is an abstract class?


An abstract class is a class that consists of abstract methods. These methods are
basically declared but not defined. If these methods are to be used in some
subclass, they need to be exclusively defined in the subclass.

Can you create an instance of an abstract class?


No. Instances of an abstract class cannot be created because it does not have a
complete implementation. However, instances of subclass inheriting the abstract
class can be created.

32. What is an interface?


It is a concept of OOPs that allows you to declare methods without defining them.
Interfaces, unlike classes, are not blueprints because they do not contain detailed
instructions or actions to be performed. Any class that implements an interface
defines the methods of the interface.

Differentiate between data abstraction and encapsulation.


Data abstraction Encapsulation

Solves the problem at the implementation


Solves the problem at the design level
level

Allows showing important aspects while Binds code and data together into a single
hiding implementation details unit and hides it from the world

What is exception handling?

Exception handling in Object-Oriented Programming is a very important concept


that is used to manage errors. An exception handler allows errors to be thrown and
caught and implements a centralized mechanism to resolve them.

What is a try/ catch block?

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.

49. What is a finally block?

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.

What are the limitations of OOPs?

 Usually not suitable for small problems


 Requires intensive testing
 Takes more time to solve the problem
 Requires proper planning
 The programmer should think of solving a problem in terms of objects

What is the output of the following Java program?


class Automobile {
private String drive() {
return "Driving vehicle";
}
}

class Car extends Automobile {


protected String drive() {
return "Driving car";
}
}

public class ElectricCar extends Car {

@Override
public final String drive() {
return "Driving an electric car";
}

public static void main(String[] wheels) {


final Car car = new ElectricCar();
System.out.print(car.drive());
}
}

Driving an electric car

What is the output of the following Java program?

class Demo{
public Demo(int i){
System.out.println("int");
}

public void Demo(short s){


System.out.println("short");
}
}

public class Test{

public static void main(String[] args){


short s = 10;
Demo demo = new Demo(s);
}
}

a) int

b) short
c) Compile-time error

d) Run-time error

Answer:

a) int

Exception Handling
How are exceptions handled in Java?

In Java, exceptions could be handled in the following ways:

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.

What is exception propagation in Java?

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.

What are runtime exceptions in Java?

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:

Can you catch and handle Multiple Exceptions in Java?

There are three ways to handle multiple exceptions in Java:

 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

Explain Java Exception Hierarchy.

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.

What happens when an exception is thrown by the main method?

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

Is it possible to throw an Exception inside a Lambda Expression’s body?

Yes, it is possible. However, we need to note two points:

 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:

List<Integer> list = Arrays.asList(2,3,5,10,20);


list.forEach(i -> {
if (i < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed.");
}
System.out.println(i);
});

 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.

Write a program to join two ArrayList into one single ArrayList.


Given two ArrayLists in Java, our task is to join these ArrayLists.
 Java

// Java program to demonstrate


// How to join ArrayList

import java.util.*;

public class GFG {


public static void main(String args[])
{

ArrayList<String> list_1 = new ArrayList<String>();

list_1.add("Geeks");
list_1.add("For");
list_1.add("ForGeeks");

// Print the ArrayList 1


System.out.println("ArrayList 1: " + list_1);

ArrayList<String> list_2 = new ArrayList<String>();

list_2.add("GeeksForGeeks");
list_2.add("A computer portal");

// Displaying the ArrayList 2


System.out.println("ArrayList 2: " + list_2);

// using Collection.addAll() method to join two


// arraylist
list_1.addAll(list_2);

// Print the joined ArrayList


System.out.println("Joined ArrayLists: " + list_1);
}
}

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 you use HashMap in a multithreaded Java application?


In a multi-threaded environment, if multiple threads alter the map structurally, such as
adding, removing, or modifying mappings, the internal data structure of HashMap may
become corrupted and there may be some missing links, incorrect entries, and the map
itself may become completely useless. Thus, you should not use HashMap in a
concurrent application; instead, use ConcurrentHashMap or Hashtable which is thread-
safe. The ConcurrentHashMap includes all the Hashtable’s methods as well as full
concurrency of retrievals and updates.
How did ThreadSafeConcurrentHashMap become thread-safe?
 java.util.Concurrent.ConcurrentHashMap class provides thread safety by
dividing the map into segments, which allows the lock to be taken only once
per segment, i.e, once for each thread.
 The read operation in ConcurrentHashMap does not require a lock.

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.

How to make a Collection Read-Only in Java?


Creating a Read-Only Collection involves restricting the object to only fetching the data
and not adding or removing data. Java has different methods for different Collection
types like unmodifiableCollection(), unmodifiableMap(), ununmodifiableSet(), etc.
java.util.The collections class defines all methods. The unmodifiableCollection()
method creates a Read-Only collection. It requires a reference to the Collection class. If
we have an object of Set Interface, we can use ununmodifiableSet() to make Read-
Only.

Why array is not a collection?


The array is not a collection, it is all because of the difference in the functionality
between collections and arrays few of which are mentioned below:
 The size of the Array can’t be changed once declared
 Arrays can hold only homogeneous data types elements.
 The array can hold both primitive datatypes and objects whereas in
collections it is only able to hold wrapper objects.
 Can you add a null element into a TreeSet or HashSet?
 In HashSet, only one null element can be added but in TreeSet it can’t be
added as it makes use of NavigableMap for storing the elements. This is
because the NavigableMap is a subtype of SortedMap that doesn’t allow null
keys. So, in case you try to add null elements to a TreeSet, it will throw a
NullPointerException.
 24. Explain the emptySet() method in the Collections
framework?
 The Collections.emptySet() is used to return the empty immutable Set while
removing the null elements. The set returned by this method is serializable.
Below is the method declaration of emptySet().
 Syntax:

1public static final <T> Set<T> emptySet()


 25. What is LinkedHashSet in Java Collections Framework?
 A java.util.LinkedHashSet is a subclass of the HashSet class and implements
the Set interface. It is an ordered version of HashSet which maintains a
doubly-linked List across all elements contained within. It preserves the
insertion order and contains only unique elements like its parent class.
 Syntax:

1LinkedHashSet<String> hs = new LinkedHashSet<String>();


Differentiate between Collection and Collections.

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

Differentiate between List and Map.

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)

How do you test protected Java methods using JUnit?


Since protected methods are accessible to everyone inside the same package they are
declared, you can put your JUnit test class also on the same package to test them. But, don't
mix your test code with real code, instead, put them on a different source tree. You can use a
Maven-like structure to organize your test and source classes in different folders.

Can you test a private method using JUnit?


Well, since private methods are not accessible outside the class they are declared, it's not
possible to test them using JUnit directly, but you can use Reflection to make them accessible
by calling setAccessible(true) before testing. Another way to test private methods is via public
methods, which uses them. In general, testing the private method is also an indication that
those methods should be moved into another class to promote reusability.

What are Parameterized tests in Junit?


The latest addition to JUnit 4 is the "Parameterized tests" feature, which empowers
developers to execute a test repeatedly with different values. With this feature,
instead of creating multiple methods for each value, developers can reuse a single
test method, leading to more efficient and succinct testing.

How do you perform integration testing


using JUnit?
Integration testing is a type of testing that verifies that different components of a
system work together correctly. JUnit, the widely used testing framework in the Java
ecosystem, can be used to perform integration testing. Here are the general steps
you can follow to perform integration testing using JUnit:

1. Identify the components to be tested: You should identify the


components of your system that need to be tested as part of the
integration testing process. This may include different modules or
subsystems that work together to provide a specific functionality.

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.

3. Mock objects: When testing interactions between components, it may


not be feasible or desirable to use the actual components in the test. You
may need to mock some of the objects or dependencies that the
components rely on, to simulate the expected behavior.

4. Configure the test environment: You should configure the test


environment to ensure that it matches the production environment as
closely as possible. This may include setting up test databases,
configuring test data, and deploying your application on a test server.

5. Use JUnit annotations: JUnit annotations can be used to control the


order in which tests are run, to group tests, to initialize resources before
tests are run, and to perform clean-up operations after tests are
completed.

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

What benefits come with using GIT?

 Data replication and redundancy are both possible.

 It is a service with high availability.

 There can only be one Git directory per repository.

 Excellent network and disc performance are achieved.

 On any project, collaboration is very simple.

Name a few Git commands with their function.

 Git config - Configure the username and email address


 Git add - Add one or more files to the staging area

 Git diff - View the changes made to the file

 Git init - Initialize an empty Git repository

 Git commit - Commit changes to head but not to the remote repository

What does the git push command do?

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.

What do you understand about the Git merge conflict?

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.

How do you resolve conflicts in Git?

Here are the steps that will help you resolve conflicts in Git:

 Identify the files responsible for the conflicts.

 Implement the desired changes to the files

 Add the files using the git add command.

 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.

What do you know about Git Stash?

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)

You might also like