Showing posts with label JavaInterview. Show all posts
Showing posts with label JavaInterview. Show all posts

Monday, May 20, 2024

Java interview questions for 10 years Experienced

1. What are some of the important features that are introduced in Java 8?

There are many features important for development using Java that were

implemented in Java 8. Some of these features are as follows:

•Lambda expressions

•Default methods for interfaces

•Functional interface

•Stream API

•Date API

2. What is a lambda expression?

Within Angular, the view embodies the graphical user interface (UI) of an

application. Its primary role involves presenting the data sourced from the

component and managing user interactions. Constructed through HTML

templates, the view dynamically renders and adjusts its content in accordance

with the component’s data and the application’s logic.

The following is the structure of a lambda expression:

1 (Argument List) ->{expression;} or

2 (Argument List) ->{statements;}

3. What are the most important advantages of using Java 8?

The introduction of Java 8 has been proven to be very helpful for programmers

in the following ways:

•Code is now highly readable

•More reusability of code

•Code size is now very compact

•Minimum boilerplate code

•Easier testability methods

•Parallel execution and operations

4. What is the meaning of functional interfaces in Java 8?

Functional interfaces in Java 8 are interfaces having a single abstract method.

Following are the three types of methods that can be present:

•The static method

•The default method

•The overridden class method

5. What are the core API classes for date and time in Java 8?

There are three main core API classes for date and time in Java 8 as given

below:

•LocalDate

•LocalTime•LocalDateTime

6. What are PermGen and Metaspace in Java 8?

The Java Virtual Machine has been using PermGen for class storage until Java

7. It is now superseded by Metaspace.

Metaspace has a huge advantage over PermGen that makes the former grow

dynamically without any constraint, while PermGen has a fixed maximum size.

7. What is the use of the optional keyword in Java 8?

The optional keyword is used in Java 8 to avoid the occurrence of the

NullPointerException.

An optional object can be created easily using the empty() static method as

shown below:

@Test

public void whenCreatesEmptyOptional_thenCorrect() {

Optional<String> empty = Optional.empty();

assertFalse(empty.isPresent());

}

8. What is a supplier in Java 8?

A supplier is a simple functional interface in Java 8 that does not take in any

argument. It is used as an assignment target when making use of lambda

expressions.

The following is an example that denotes the usage of a supplier:

import java.util.function.Supplier;

public class Java8SupplierExample {

public static void main(String[] args) {

Supplier<String> supplier= ()-> "HelloLearners";

System.out.println(supplier.get());

}

}

9.What is a consumer in Java 8?

Similar to a predicate, a consumer is a functional interface with a single

argument in Java 8. However, unlike a predicate, a consumer does not return

any value and is commonly used for lambda expressions. Below is an example

code snippet that demonstrates the usage of the consumer interface to print a

string:

import java.util.function.Consumer;

public class Java8ConsumerExample {

public static void main(String[] args) {

Consumer<String>; consumerString = s -> System.out.println(s);

consumerString.accept("HelloWorld");}}

10. Can you name the common types of functional interfaces in the standard

library?

There are many functional interface types in the standard library, and some of

them are as follows:

•BiFuction

•BinaryOperator

•Consumer

•Predicate

•Supplier

•UnaryOperator

11. What are the similarities between map and flatMap stream operations in

Java 8?

Both the map and flatMap operations are types of intermediate stream

operations. They accept a function as input and utilize this function to perform

different actions on the stream elements.

12. Can you give examples of intermediate operations in Java 8?

The examples that are widely used in intermediate operations are:

•Distinct()

•Limit(long n)

•Filter(Predicate)

•Map(Function)

•skip(long n)

•

13. What are some of the examples of terminal operations in Java 8?

Following are some of the examples of terminal operations in Java 8:

•Count

•Min

•Max

•Reduce

•toArray

•anymatch

•allMatch

Spring Boot Questions

14. What annotations are used to create an Interceptor?

A prominent functionality of Spring Boot, Interceptor uses the annotated class

@Component, and it implements the interface HandlerInterceptor.

The interface contains 3 main methods, which are:

The preHandle() Method − preHandle() is used for intercepting the request prior

to the implementation of the handler. If preHandle() returns a “true” booleanvalue, developers can continue with handler execution. If preHandle() returns a

“false” boolean value, developers should stop the handler execution

15. What is a Swagger in Spring Boot?

Swagger is used for clearly detailing and documenting RESTful APIs in a

machine-readable and human-readable format, which is easily comprehensible for

testers and developers, as well as individuals having little knowledge of source

code.

Enabling hassle-free application discovery, development, and integration, Swagger

allows API consumers to interact with remote services with minimum

implementation logic.

16. What are Profiles in Spring Boot?

Profiles in the Spring framework enables users to map components and beans to

specific profiles, such as the Development (dev) profile, Production (prod)

profile, or the Test profile.

In Spring Boot, the annotation @Profile is used to map components and beans

to a certain profile.

What are the important features of Spring Boot?

Important features of Spring Boot are:

Web Development

Spring Application

Application occasions and listeners

Admin highlights

YAML Support

Type-safe Configuration

Externalized Configuration

Properties Files

Logging and Security

17.Is it possible to replace or override the Embedded Tomcat server in Spring

Boot?

Yes, it is possible to replace the Embedded Tomcat with any other servers by

using the starter dependencies. For that, you can use spring-boot-starter-jetty or

as a dependency for according you to your need.

18. What is the difference between Spring and Spring Boot?

Difference between Spring and Spring boot are as follows:

Spring –

1.Is a dependency injection framework.

2.It is basically used to manage the life cycle of java classes (beans). It

consists of a lot of boilerplate configuration.

3.Uses XML based configuration.

4.It takes time to have a spring application up and running and it’s mainly

because of boilerplate code.Spring boot-

1.It is a suite of pre- configured frameworks and technologies which helps to

remove boilerplate configuration.

2.Uses annotations.

3.It is used to create a production-ready code.

Hibernate Interview Questiions

19. What are fetching strategies? Which strategies do Hibernate support?

Hibernate uses a fetching strategy for retrieving associated objects when the

application has to navigate the association. The strategies can be declared in the

O/R mapping metadata or overridden by a particular HQL or criteria query.

Hibernate supports the following fetching strategies:

Join fetching

Batch fetching

Immediate fetching

Select fetching

Subselect fetching

Lazy collection fetching

"No-proxy" fetching

"Extra-lazy" collection fetching

Proxy fetching

Lazy attribute fetching(Naming Directory Interface)

Database - MySQL, PostgreSQL, Oracle

20. What are the main elements of the hibernate framwork?

hibernate framwork consists of the following main elements:

SessionFactory: It gives a factory method to create session objects and

get clients of ConnectionProvider. It is immutable and holds a second-

level cache (optional) of data.

Session: A short-lived object acting as an interface between the Java

application objects and database data. It is usually used to generate query,

transaction, and criteria objects. It has a first-level cache (mandatory) of

data.

Transaction: An object specifying the atomic unit of work. It has

methods for transaction management and is optional.

TransactionFactory: A factory of transaction objects. It is optional.

ConnectionProvider: A factory of JDBC connection objects. It is optional

and gives abstraction to the application from the DriverManager.

21. Can we define an entity class final in Hibernate?

No, we should not declare the entity class final because Hibernate employs

objects for lazy loading of data and proxy classes and hits the database only ifit is absolutely necessary. You can achieve the same by extending the entity

bean. However, if you declare the entity class (or bean) final, then it can't be

extended. As a result, lazy loading won't be supported

22.What is a view in SQL? How to create a view?

A view is a virtual table based on the result-set of an SQL statement. We can

create it using create view syntax.

CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

23.What are the uses of view?

1. Views can represent a subset of the data contained in a table; consequently,

a view can limit the degree of exposure of the underlying tables to the outer

world: a given user may have permission to query the view, while denied

access to the rest of the base table.

2. Views can join and simplify multiple tables into a single virtual table.

3. Views can act as aggregated tables, where the database engine aggregates

data (sum, average, etc.) and presents the calculated results as part of the data.

4. Views can hide the complexity of data.

5. Views take very little space to store; the database contains only the

definition of a view, not a copy of all the data which it presents.

6. Depending on the SQL engine used, views can provide extra security.

24. What is a Trigger?

A Trigger is a code associated with insert, update or delete operations. The

code is executed automatically whenever the associated query is executed on a

table. Triggers can be useful to maintain integrity in the database.

25. What is a transaction? What are ACID properties?

A Database Transaction is a set of database operations that must be treated as

a whole, which means either all operations are executed or none of them.An

example can be a bank transaction from one account to another account. Either

both debit and credit operations must be executed or none of them.ACID

(Atomicity, Consistency, Isolation, Durability) is a set of properties that

guarantee that database transactions are processed reliably.

26. What are indexes?

A database index is a data structure that improves the speed of data retrieval

operations on a database table at the cost of additional writes and the use ofmore storage space to maintain the extra copy of data.Data can be stored only

in one order on a disk. To support faster access according to different values,

faster search like binary search for different values is desired, For this purpose,

indexes are created on tables. These indexes need extra space on the disk, but

they allow faster search according to different frequently searched values.

27. What are clustered and non-clustered Indexes?

Clustered indexes are the index according to which data is physically stored on

a disk. Therefore, only one clustered index can be created on a given database

table.

Non-clustered indexes don’t define the physical ordering of data, but logical

ordering. Typically, a tree is created whose leaf point to disk records. B-Tree

or B+ tree are used for this purpose.

28. What is a Live Lock?

Livelock situation can be defined as when two or more processes continually

repeat the same interaction in response to changes in the other processes

without doing any useful work These processes are not in the waiting state, and

they are running concurrently. This is different from a deadlock because in a

deadlock all processes are in the waiting state.

29.What are temporary tables? When are they useful?

Temporary tables exist solely for a particular session, or whose data persists for

the duration of the transaction. The temporary tables are generally used to

support specialized rollups or specific application processing requirements. Unlike

a permanent table, space is not allocated to a temporary table when it is

created. Space will be dynamically allocated for the table as rows are inserted.

The CREATE GLOBAL TEMPORARY TABLE command is used to create a

temporary table in Oracle.

Monday, May 13, 2024

java oops interview questions for 5 years experience

 Basic OOPs Interview Questions

1. What is meant by the term OOPs?

OOPs refers to Object-Oriented Programming. It is the programming paradigm that

is defined using objects. Objects can be considered as real-world instances of

entities like class, that have some characteristics and behaviors.

2. What is the need for OOPs?

There are many reasons why OOPs is mostly preferred, but the most important among them are:

i.OOPs helps users to understand the software easily, although they don’t know the actual

implementation.

ii.With OOPs, the readability, understandability, and maintainability of the code increase multifold.

iii.Even very big software can be easily written and managed easily using OOPs.

3. What are some major Object Oriented Programming languages?

The programming languages that use and follow the Object-Oriented Programming paradigm or

OOPs, are known as Object-Oriented Programming languages. Some of the major Object-Oriented

Programming languages include:

Java

C++

Javascript

Python

PHP

4. What are some other programming paradigms other than OOPs?

Programming paradigms refers to the method of classification of programming languages based on

their features. There are mainly two types of Programming Paradigms:

Imperative Programming Paradigm

Declarative Programming Paradigm

1. Imperative Programming Paradigm: Imperative programming focuses on HOW

to execute program logic and defines control flow as statements that change a program state.

This can be further classified as:

a)Procedural Programming Paradigm: Procedural programming specifies the steps a program

must take to reach the desired state, usually read in order from top to bottom.

b)Object-Oriented Programming or OOP: Object-oriented programming (OOP) organizes

programs as objects, that contain some data and have some behavior.

c)Parallel Programming: Parallel programming paradigm breaks a task into subtasks and

focuses on executing them simultaneously at the same time.

2. Declarative Programming Paradigm: Declarative programming focuses on WHAT to execute

and defines program logic, but not a detailed control flow. Declarative paradigm can be

further classified into:

a) Logical Programming Paradigm: Logical programming paradigm is based on formal logic,which refers to a set of sentences expressing facts and rules about how to solve a problem

b) Functional Programming Paradigm: Functional programming is a programming paradigm

where programs are constructed by applying and composing functions.

c) Database Programming Paradigm: Database programming model is used to manage data

and information structured as fields, records, and files.

5. What is meant by Structured Programming?

Structured Programming refers to the method of programming which consists of a completely

structured control flow. Here structure refers to a block, which contains a set of rules, and

has a definitive control flow, such as (if/then/else), (while and for), block structures, and

subroutines.

Nearly all programming paradigms include Structured programming, including the OOPs model.

6. What are the main features of OOPs?

OOPs or Object Oriented Programming mainly comprises of the below four features, and make sure

you don't miss any of these:

 Inheritance

 Encapsulation

 Polymorphism

 Data Abstraction

7. What are some advantages of using OOPs?

 OOPs is very helpful in solving very complex level of problems.

 Highly complex programs can be created, handled, and maintained easily using object-oriented

programming.

 OOPs, promote code reuse, thereby reducing redundancy.

 OOPs also helps to hide the unnecessary details with the help of Data Abstraction.

 OOPs, are based on a bottom-up approach, unlike the Structural programming paradigm, which

uses a top-down approach.

 Polymorphism offers a lot of flexibility in OOPs.8. Why is OOPs so popular?

OOPs programming paradigm is considered as a better style of programming. Not only it

helps in writing a complex piece of code easily, but it also allows users to handle and

maintain them easily as well. Not only that, the main pillar of OOPs - Data Abstraction,

Encapsulation, Inheritance, and Polymorphism, makes it easy for programmers to solve

complex scenarios. As a result of these, OOPs is so popular.

Advanced OOPs Interview Questions

1. What is a class?

A class can be understood as a template or a blueprint, which contains some values, known as

member data or member, and some set of rules, known as behaviors or functions. So when an object

is created, it automatically takes the data and functions that are defined in the class.

Therefore the class is basically a template or blueprint for objects. Also one can create as many

objects as they want based on a class.

For example, first, a car’s template is created. Then multiple units of car are created based on that

template.

2. What is an object?

An object refers to the instance of the class, which contains the instance of the members and

behaviors defined in the class template. In the real world, an object is an actual entity to which a

user interacts, whereas class is just the blueprint for that object. So the objects consume space and

have some characteristic behavior.

For example, a specific car.

3. What is encapsulation?

One can visualize Encapsulation as the method of putting everything that is required to do

the job, inside a capsule and presenting that capsule to the user. What it means is that by

Encapsulation, all the necessary data and methods are bind together and all the unnecessary

details are hidden to the normal user. So Encapsulation is the process of binding data

members and methods of a program together to do a specific job, without revealing

unnecessary details.

Encapsulation can also be defined in two different ways:

1) Data hiding: Encapsulation is the process of hiding unwanted information, such as

restricting access to any member of an object.

2) Data binding: Encapsulation is the process of binding the data members and the methods

together as a whole, as a class.

4. What is Polymorphism?

Polymorphism is composed of two words - “poly” which means “many”, and “morph” which

means “shapes”. Therefore Polymorphism refers to something that has many shapes.In OOPs, Polymorphism refers to the process by which some code, data, method, or object behaves

differently under different circumstances or contexts. Compile-time polymorphism and Run time

polymorphism are the two types of polymorphisms in OOPs languages.

5. What is Compile time Polymorphism and how is it different from Runtime Polymorphism?

Compile Time Polymorphism: Compile time polymorphism, also known as Static Polymorphism,

refers to the type of Polymorphism that happens at compile time. What it means is that the compiler

decides what shape or value has to be taken by the entity in the picture.

Example:

// In this program, we will see how multiple functions are created with the same name,

// but the compiler decides which function to call easily at the compile time itself.

class CompileTimePolymorphism{

// 1st method with name add

public int add(int x, int y){

return x+y;

}

// 2nd method with name add

public int add(int x, int y, int z){

return x+y+z;

}

// 3rd method with name add

public int add(double x, int y){

return (int)x+y;

}

// 4th method with name add

public int add(int x, double y){

return x+(int)y;

}

}

class Test{

public static void main(String[] args){CompileTimePolymorphism demo=new CompileTimePolymorphism();

// In the below statement, the Compiler looks at the argument types and decides to call method 1

System.out.println(demo.add(2,3));

// Similarly, in the below statement, the compiler calls method 2

System.out.println(demo.add(2,3,4));

// Similarly, in the below statement, the compiler calls method 4

System.out.println(demo.add(2,3.4));

// Similarly, in the below statement, the compiler calls method 3

System.out.println(demo.add(2.5,3));

}

}

In the above example, there are four versions of add methods. The first method takes two parameters

while the second one takes three. For the third and fourth methods, there is a change of order of

parameters. The compiler looks at the method signature and decides which method to invoke for a

particular method call at compile time.

Runtime Polymorphism: Runtime polymorphism, also known as Dynamic Polymorphism, refers to the

type of Polymorphism that happens at the run time. What it means is it can't be decided by the

compiler. Therefore what shape or value has to be taken depends upon the execution. Hence the

name Runtime Polymorphism.

Example:

class AnyVehicle{

public void move(){

System.out.println(“Any vehicle should move!!”);

}

}

class Bike extends AnyVehicle{

public void move(){

System.out.println(“Bike can move too!!”);

}

}

class Test{

public static void main(String[] args){

AnyVehicle vehicle = new Bike();

// In the above statement, as you can see, the object vehicle is of type AnyVehicle

// But the output of the below statement will be “Bike can move too!!”,

// because the actual implementation of object ‘vehicle’ is decided during runtime vehicle.move();

vehicle = new AnyVehicle();

// Now, the output of the below statement will be “Any vehicle should move!!”,

vehicle.move();

}

}

As the method to call is determined at runtime, as shown in the above code, this is called runtime

polymorphism.

6. How does C++ support Polymorphism?

C++ is an Object-oriented programming language and it supports Polymorphism as well:

 Compile Time Polymorphism: C++ supports compile-time polymorphism with the help of

features like templates, function overloading, and default arguments.

 Runtime Polymorphism: C++ supports Runtime polymorphism with the help of features like

virtual functions. Virtual functions take the shape of the functions based on the type of

object in reference and are resolved at runtime.

7. What is meant by Inheritance?

The term “inheritance” means “receiving some quality or behavior from a parent to an offspring.” In

object-oriented programming, inheritance is the mechanism by which an object or class (referred to asa child) is created using the definition of another object or class (referred to as a parent). Inheritance

not only helps to keep the implementation simpler but also helps to facilitate code reuse.

8. What is Abstraction?

If you are a user, and you have a problem statement, you don't want to know how the components

of the software work, or how it's made. You only want to know how the software solves your

problem. Abstraction is the method of hiding unnecessary details from the necessary ones. It is one

of the main features of OOPs.

For example, consider a car. You only need to know how to run a car, and not how the wires are

connected inside it. This is obtained using Abstraction.

9. How much memory does a class occupy?

Classes do not consume any memory. They are just a blueprint based on which objects are created.

Now when objects are created, they actually initialize the class members and methods and therefore

consume memory.

10. Is it always necessary to create objects from class?

No. An object is necessary to be created if the base class has non-static methods. But if the class

has static methods, then objects don’t need to be created. You can call the class method directly in

this case, using the class name.

11. What is a constructor?

Constructors are special methods whose name is the same as the class name. The constructors serve

the special purpose of initializing the objects.

For example, suppose there is a class with the name “MyClass”, then when you instantiate this class,

you pass the syntax:

MyClass myClassObject = new MyClass();

Now here, the method called after “new” keyword - MyClass(), is the constructor of this class. This

will help to instantiate the member data and methods and assign them to the object myClassObject.

12. What are the various types of constructors in C++?

The most common classification of constructors includes:

Default constructor: The default constructor is the constructor which doesn’t take any argument. It has

no parameters.

class ABC

{

int x;

ABC()

{

x = 0;

}

}

Parameterized constructor: The constructors that take some arguments are known as parameterized

constructors.

class ABC{

int x;

ABC(int y)

{

x = y;

}

}

Copy constructor: A copy constructor is a member function that initializes an object using another

object of the same class.

class ABC

{

int x;

ABC(int y)

{

x = y;

}

// Copy constructor

ABC(ABC abc)

{

x = abc.x;

}

}

13. What is a copy constructor?

Copy Constructor is a type of constructor, whose purpose is to copy an object to another. What it

means is that a copy constructor will clone an object and its values, into another object, is provided

that both the objects are of the same class.

14. What is a destructor?

Contrary to constructors, which initialize objects and specify space for them, Destructors are also

special methods. But destructors free up the resources and memory occupied by an object. Destructors

are automatically called when an object is being destroyed.

15. Are class and structure the same? If not, what's the difference between a class and a

structure?

No, class and structure are not the same. Though they appear to be similar, they have differences

that make them apart. For example, the structure is saved in the stack memory, whereas the class is

saved in the heap memory. Also, Data Abstraction cannot be achieved with the help of structure, but

with class, Abstraction is majorly used.

16. Explain Inheritance with an example?

Inheritance is one of the major features of object-oriented programming, by which an entity inherits

some characteristics and behaviors of some other entity and makes them their own. Inheritance helps

to improve and facilitate code reuse.

Let's take three different vehicles - a car, truck, or bus. These three are entirely different from one

another with their own specific characteristics and behavior. But. in all three, you will find some

common elements, like steering wheel, accelerator, clutch, brakes, etc. Though these elements are used

in different vehicles, still they have their own features which are common among all vehicles. This is

achieved with inheritance. The car, the truck, and the bus have all inherited the features like steering

wheel, accelerator, clutch, brakes, etc, and used them as their own. Due to this, they did not have to

create these components from scratch, thereby facilitating code reuse.

17. Are there any limitations of Inheritance?

Yes, with more powers comes more complications. Inheritance is a very powerful feature in OOPs,

but it has some limitations too. Inheritance needs more time to process, as it needs to navigate

through multiple classes for its implementation. Also, the classes involved in Inheritance - the base

class and the child class, are very tightly coupled together. So if one needs to make some changes,

they might need to do nested changes in both classes. Inheritance might be complex for

implementation, as well. So if not correctly implemented, this might lead to unexpected errors or

incorrect outputs.

18. What are the various types of inheritance?

The various types of inheritance include:

 Single inheritance

 Multiple inheritances

 Multi-level inheritance

 Hierarchical inheritance

 Hybrid inheritance

19. What is a subclass?

The subclass is a part of Inheritance. The subclass is an entity, which inherits from another

class. It is also known as the child class.

20. Define a superclass?

Superclass is also a part of Inheritance. The superclass is an entity, which allows subclasses or child

classes to inherit from itself.

21. What is an interface?

An interface refers to a special type of class, which contains methods, but not their

definition. Only the declaration of methods is allowed inside an interface. To use an

interface, you cannot create objects. Instead, you need to implement that interface and define

the methods for their implementation.

22. What is meant by static polymorphism?

Static Polymorphism is commonly known as the Compile time polymorphism. Static polymorphism is

the feature by which an object is linked with the respective function or operator based on the values

during the compile time. Static or Compile time Polymorphism can be achieved through Method

overloading or operator overloading.

23. What is meant by dynamic polymorphism?

Dynamic Polymorphism or Runtime polymorphism refers to the type of Polymorphism in OOPs, by

which the actual implementation of the function is decided during the runtime or execution. The

dynamic or runtime polymorphism can be achieved with the help of method overriding.

24. What is the difference between overloading and overriding?

Overloading is a compile-time polymorphism feature in which an entity has multiple implementations

with the same name. For example, Method overloading and Operator overloading.

Whereas Overriding is a runtime polymorphism feature in which an entity has the same name, but its

implementation changes during execution. For example, Method overriding.

25. How is data abstraction accomplished?

Data abstraction is accomplished with the help of abstract methods or abstract classes.

26. What is an abstract class?

An abstract class is a special class containing abstract methods. The significance of abstract class is

that the abstract methods inside it are not implemented and only declared. So as a result, when a

subclass inherits the abstract class and needs to use its abstract methods, they need to define and

implement them.

27. How is an abstract class different from an interface?

Interface and abstract classes both are special types of classes that contain only the methods

declaration and not their implementation. But the interface is entirely different from an abstract class.

The main difference between the two is that when an interface is implemented, the subclass must

define all its methods and provide its implementation. Whereas in object-oriented programming, when

a subclass inherits from an abstract class with abstract methods, the subclass is generally required to

provide concrete implementations for all of those abstract methods in the abstract class unless the

subclass itself is declared as abstract.

Also, an abstract class can contain abstract methods as well as non-abstract methods.

28. What are access specifiers and what is their significance?

Access specifiers, as the name suggests, are a special type of keywords, which are used to

control or specify the accessibility of entities like classes, methods, etc. Some of the accessspecifiers or access modifiers include “private”, “public”, etc. These access specifiers also play a

very vital role in achieving Encapsulation - one of the major features of OOPs.

29. What is an exception?

An exception can be considered as a special event, which is raised during the execution of a program

at runtime, that brings the execution to a halt. The reason for the exception is mainly due to a

position in the program, where the user wants to do something for which the program is not

specified, like undesirable input.

30. What is meant by exception handling?

No one wants its software to fail or crash. Exceptions are the major reason for software failure. The

exceptions can be handled in the program beforehand and prevent the execution from stopping. This

is known as exception handling.

So exception handling is the mechanism for identifying the undesirable states that the program can

reach and specifying the desirable outcomes of such states.

Try-catch is the most common method used for handling exceptions in the program.

31. What is meant by Garbage Collection in OOPs world?

Object-oriented programming revolves around entities like objects. Each object consumes memory and

there can be multiple objects of a class. So if these objects and their memories are not handled

properly, then it might lead to certain memory-related errors and the system might fail.

Garbage collection refers to this mechanism of handling the memory in the program. Through garbage

collection, the unwanted memory is freed up by removing the objects that are no longer needed.

32. Can we run a Java application without implementing the OOPs concept?

No. Java applications are based on Object-oriented programming models or OOPs concept, and hence

they cannot be implemented without it.

However, on the other hand, C++ can be implemented without OOPs, as it also supports the C-like

structural programming model.

1. What is the output of the below code?

#include<iostream>

using namespace std;

class BaseClass1 {

public:

BaseClass1()

{ cout << " BaseClass1 constructor called" << endl; }

};

class BaseClass2 {

public:

BaseClass2()

{ cout << "BaseClass2 constructor called" << endl; }

};

class DerivedClass: public BaseClass1, public BaseClass2 {

public:

DerivedClass()

{ cout << "DerivedClass constructor called" << endl; }

};

int main()

{

DerivedClass derived_class;

return 0;

}Output:

BaseClass1 constructor called

BaseClass2 constructor called

DerivedClass constructor called

Reason:

The above program demonstrates Multiple inheritances. So when the Derived class’s constructor is

called, it automatically calls the Base class's constructors from left to right order of inheritance.

2. What will be the output of the below code?

class Scaler

{

static int i;

static

{

System.out.println(“a”);

i = 100;

}

}

public class StaticBlock

{

static

{

System.out.println(“b”);

}

public static void main(String[] args)

{

System.out.println(“c”);

System.out.println(Scaler.i);

}

}

Output:

b

c

a

100

Reason:

Firstly the static block inside the main-method calling class will be implemented. Hence ‘b’ will be

printed first. Then the main method is called, and now the sequence is kept as expected.

3. Predict the output?

#include<iostream>

using namespace std;

class ClassA {

public:

ClassA(int ii = 0) : i(ii) {}

void show() { cout << "i = " << i << endl;}

private:

int i;

};

class ClassB {

public:

ClassB(int xx) : x(xx) {}

operator ClassA() const { return ClassA(x); }private:

int x;

};

void g(ClassA a)

{ a.show(); }

int main() {

ClassB b(10);

g(b);

g(20);

getchar();

return 0;

}

Output:

i = 10

i = 20

Reason:

ClassA contains a conversion constructor. Due to this, the objects of ClassA can have integer values.

So the statement g(20) works. Also, ClassB has a conversion operator overloaded. So the statement

g(b) also works.

4. What will be the output in below code?

public class Demo{

public static void main(String[] arr){

System.out.println(“Main1”);

}

public static void main(String arr){

System.out.println(“Main2”);

}

}

Output:

Main1

Reason:

Here the main() method is overloaded. But JVM only understands the main method which has a

String[] argument in its definition. Hence Main1 is printed and the overloaded main method is

ignored.

5. Predict the output?

#include<iostream>

using namespace std;

class BaseClass{

int arr[10];

};

class DerivedBaseClass1: public BaseClass { };

class DerivedBaseClass2: public BaseClass { };

class DerivedClass: public DerivedBaseClass1, public DerivedBaseClass2{};

int main(void)

{

cout<<sizeof(DerivedClass);

return 0;

}

Output:

If the size of the integer is 4 bytes, then the output will be 80.Reason:

Since DerivedBaseClass1 and DerivedBaseClass2 both inherit from class BaseClass, DerivedClass

contains two copies of BaseClass. Hence it results in wastage of space and a large size output. It

can be reduced with the help of a virtual base class.

6. What is the output of the below program?

#include<iostream>

using namespace std;

class A {

public:

void print()

{ cout <<" Inside A::"; }

};

class B : public A {

public:

void print()

{ cout <<" Inside B"; }

};

class C: public B {

};

int main(void)

{

C c;

c.print();

return 0;

}

Output:

Inside B

Reason:

The above program implements a Multi-level hierarchy. So the program is linearly searched up until a

matching function is found. Here, it is present in both classes A and B. So class B’s print() method

is called.

Sunday, May 12, 2024

Java Interview Questions

 List of Top 15 Java Interview Questions for 2 years Experienced

Some of the Java interview questions for 2 years experience.

1. Tell me the difference between Method Overloading and Method Overriding in Java.

This is one of the core java interview questions for experienced professionals. Method Overloading

is used to increase the readability of the program.

Method Overloading has the same method name but different parameters. Method Overriding is

used for providing the specific implementation of the method. Method Overriding has the same

method and same parameters.

2. What do you mean by the class loader in Java?

In the Java Virtual Machine, the class loader is a type of subsystem. It is used for loading class files.

When you run the program, it will be first loaded by the class loader. The built-in class loaders are

of three types in Java-

•The Bootstrap Classloader is the first-class loader in JVM. It is the superclass of the

Extension class loader. It loads the rt.jar file that constitutes all the class files of Java

Standard Edition. The files being java.lang package classes, java.net package classes,

java.util packages classes, java.io packages classes, java.sql packages classes, etc.

•The Extension Classloader is the class loader of Bootstrap and the parent class loader of the

system classloader. It generally loads the jar files located inside the

$JAVA_HOME_/jre/lib/ext directory.

•The System Application Classloader is the type child class loader of the Extension class

loader. From the cross path, the System Application Classloader loads the class files. It is by

default; the classpath is set to the current directory. Therefore, it is also called the

Application class loader.

3. What do you mean by inheritance in Java?

To this Java interview question, you can answer it by saying; In Java, inheritance is a mechanism

through which an object acquires all the properties and behavior of another class. It is usually used

for Method Overriding and Code Reusability.

The concept of inheritance in Java is based on the fact that it creates new classes that are built upon

the existing classes. Therefore, these methods and fields of the parent class can be reused if we

inherit from an existing class. And also, we can add new methods and fields to our current class.

In Java, the inheritance is of five types-

•Hybrid Inheritance

•Hierarchical Inheritance

•Single-level Inheritance

•Multi-level Inheritance

•Multiple Inheritance

4. Why can we not override the static method in Java?The reasons why we cannot override the static method in Java are :

(a) The static method does not belong to the object level. Instead, it belongs to the class level. The

object decides which method can be called in the method overriding.

(b) In the static method, which is the class level method, the type reference decides on which

method is to be called without referring to the object. It concludes that the method that is called is

determined at the compile time.

If any child class defines the static method with the same signature as the parent class, then the

method in the child class hides the method in the parent class.

5. Can you tell us what the Dynamic Method Dispatch is in Java?

The Dynamic method dispatch is a process through which a call towards an overridden method is

solved at a run time. It is the object that is being referred to, not the type reference variable. It

decides which version of the overridden method needs to be executed.

6. What is a Java ClassPath?

A Java ClassPath is a type of environment variable which the Java Virtual Machine (JVM) uses to

collect all classes by the program.

7. What can be stated as a volatile keyword in Java?

If a variable will be marked as volatile, then the variable can be read from the main memory instead

of the cache memory.

8. Where does the final block not execute in Java?

To this Java interview question, you can answer it by saying; There is only one case where the final

block does not execute in Java. The final block does not execute when you run System.exit(0) in the

try or catch block in the Java programs.

9. What are the major points of distinction between StringBuffer and StringBuilder in Java?

A StringBuffer is thread-safe. Therefore, simultaneously two threads cannot call the methods of

StringBuffer. On the other hand, in comparison to StringBuffer, a StringBuilder is not known to be

thread-safe. Hence means that two threads can call the methods of StringBuilder at the same time.

On the basis of performance StringBuffer’s performance is less efficient as it is thread-safe.

Whereas StringBuilder’s performance is more efficient as it is not thread-safe.

10. Can you tell the difference between the Vector and ArrayList in Java?

You can answer this Java interview question by listing the differences between the vector and the

ArrayList.

(a) The common difference between the vector and the ArrayList in Java is that the vector is

synchronized and thread-safe while the ArrayList is not.

(b) Since vector is synchronized, it is slow, but since the ArrayList is not synchronized, it is

comparatively faster

11. Why is String immutable in Java?To this Java interview question, you can answer it by saying there are several reasons why String is

immutable or unchangeable in Java.

String pool- if you assign a value to String using the double quotes (” “), it gets stored in the string

literal pool area, and a single String can be referenced by several reference variables, which will

make it affect all reference variables if the String becomes mutable.

Classloading- String is used for the mechanism of class loading. If String becomes mutable, then it

will become a security threat because anyone can hack it.

Cache hash value-when you use String as a key in HashMap or any other collection, you can cache

its hash value. You do not need to calculate each time as it will always be constant because the

string is immutable.

12. Can you tell the difference between the HashMap and HashSet in Java?

To answer this ava interview question, HashMap implements the Map interface, which maps keys to

value. It is not synchronized, and it is not thread safe. Null keys and values are allowed, whereas

duplicate keys are not allowed.

HashMap<Integer,String> studentHashMap=new HashMap<Integer,String>();

studentHashMap.put(1, “Anushka”);

studentHashMap.put(2. “Akansha”);

In the case of HashSet, it implements a Set interface that does not allow duplicate values. As a

result, it is neither synchronized nor thread-safe.

HashSet studentSet=new HashSet();

studentSet.add(“Anushka”);

studentSet.add(“Akansha”);

studentSet.add(“Anjana”);

13. What is the Producer-Consumer Problem? What are the advantages of the Producer-

Consumer Pattern?

This is one of the advanced Java interview questions that is asked in a Java interview. The

Producer-Consumer Pattern can be implemented so that the Producer should wait if the bucket is

full. The Customer needs to wait if the bucket is empty. The classical way of solving the Producer-

Consumer Problem can be implemented by using the wait and notify method. It is to communicate

between Consumer and Producer threads and also blocks each of them on individual conditions

such as empty queue and full queue.

The Producer-Consumer Pattern is usually while writing the concurrent code and the multithreaded

code. The advantages of the Producer-Consumer Pattern are-

•The Producer does not need to know about the consumer or the number of consumers there

are. The same case goes with the Producer as well.

•The Producer and the Consumer can work at separate, different speeds. Usually, if you

monitor the speed of the consumer, then more consumers can be introduced for better

utilization.•If you functionally separate the Producer and Consumer, it can result in clean, readable, and

manageable code.

14. How do you think we can create an immutable class in Java?

An immutable class has only one state, and it is carefully instantiated by the constructor.

To create an immutable class in Java, you can follow these steps-

(a) You can make your class final so that no class will be able to extend that. Therefore, no one will

be able to override methods in this class.

(b) You can make your instance variables private, then any class will not be able to access instance

variables. You can make the final so that you cannot change it.

(c) You should not create a setter method for instance variables so that no explicit way will be there

to change the state of the instance variables.

(d) Initialize the variables in the constructor and take proper care while working with the mutable

object. You must do the deep copy in the case of mutable objects.

(e) You should return a clone of the object from the getter method so that it won’t return the original

object. After that, your original object will be intact.

15. Can you tell us the difference between the fail-safe and fail-fast iterator in java?

This is an advanced Java question for experienced professionals. To answer this question, the

difference between the Fail-fast iterator and fail-safe iterator in Java are-

fail-fast iterator- It fails as soon as they realize that the structure of the collection is changed since

the beginning of the iteration. The structural changes here are removing, adding, or updating any

element from the collection when one thread is iterating over that other collection. The fail-fast can

be implemented by maintaining a modification count. When the iteration thread will realize the

change in the count, it throws ConcurrentModificationException.

fail-safe iterator in Java- It does not throw an Exception when the collection is modified in a

structural manner while one iteration is working over it. It works on the clone collection instead of

the original collection