UpGrade Question
UpGrade Question
UpGrade Question
You can’t avoid panicking, but you can definitely prepare yourself so that when you step in that interview room. You
are confident and know you can handle anything the interviewer might throw at you.
Learn Software engineering programs online from the World’s top Universities. Earn Executive PG Programs,
Advanced Certificate Programs, or Masters Programs to fast-track your career.
Here is a compiled list of comprehensive 24 Java Interview Questions with Answers (latest 2022) that will
help you nail that confidence, and ensure you sail through the interview.
Java interview questions and answers like such make for a confident start in any interview. Whenever the
interviewer asks you any component-related question, always categorise it and give one line description. This
helps in creating a positive impression on the recruiter.
Master of Science in Computer Science from LJMU Caltech CTME Cybersecurity Certificate Program
& IIITB
The object-oriented programming language consists of classes of objects that is linked with methods (functions)
they are associated with.
These concepts of object-oriented programming can contain data and code. The procedures are a common feature
of objects that are attached to them. This helps in easy access and modification.
Some of the programming languages that consist of OOPs are C, C++, Python, and Javascript.
Since Java utilizes eight primitive datatypes — boolean, byte, char, int, float, long, short and double — which are
not objects, Java cannot be considered a 100% object-oriented language.
These types of java interview questions for freshers 2024 will stay relevant and will be asked in the coming times.
Stay updated with your answers, and always be prepared to handle these fundamental questions, so brush up on
the basics before appearing for your interview.
It helps in reusing code. It builds a relationship between two classes that builds a ‘has-a’ and ‘whole/ part’
relationship. It contains a reference to another class and is said to be having ownership of that class.
These technical-based java interview questions are asked to gauge the depth of your technical knowledge. Make
sure not to keep your answers til a bookish definition; rather, mention how the technology is important or useful in
the domain.
It is the ultimate base class for all non-primitive data types, directly or indirectly. This fundamental class provides
essential methods like equals(), hashCode(), and toString(), which are throughout Java’s class hierarchy.
Extending the Object, classes inherit a standardized interface, facilitating interoperability and enabling features like
polymorphism and object comparison.
This pivotal superclass embodies the core principles of Java’s object-oriented paradigm, forming the cornerstone of
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 3/42
3/14/24, 1:41 AM (3) New Messages!
This pivotal superclass embodies the core principles of Java s object oriented paradigm, forming the cornerstone of
the language’s rich class structure. Understanding its role empowers developers to harness the full potential of
Java’s inheritance and abstraction mechanisms.
In contrast, finalize() is a special method in the object class. It is generally overridden to release system resources
when garbage value is collected from the object.
Before appearing for the interview to tackle these types of java interview questions for freshers, you may refer to
the below-mentioned table-
Finally Finalize
It is a block. It is a method.
Can be followed by try-catch/ without it. Can be explicitly called from an application program.`
It is used to clean up the resources used in the ‘try’ Clean up the activities related to the object before the
block. destruction.
A non-static nested class is called an inner class. Inner classes are associated with the objects of the class and
they can access all methods and variables of the outer class.
These types of java interview questions for freshers 2024 are relevant and will be asked in the coming times.
Some of the features of system class include
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 4/42
3/14/24, 1:41 AM (3) New Messages!
Daemon threads provide background support to non-daemon threads, allowing the program to terminate without
waiting for them to finish their execution. These threads are useful for tasks like garbage collection or logging,
ensuring that essential operations are managed efficiently and enhancing overall performance and responsiveness
of Java applications.
Daemon threads in Java, marked by setDaemon(true), are crucial in maintaining a well-organized and responsive
application environment. Unlike user threads, daemon threads don’t prevent the program from exiting once the
main execution concludes. They gracefully terminate alongside the main thread, handling auxiliary tasks
seamlessly.
By understanding and skillfully implementing daemon threads, developers can optimize resource utilization and
enhance the overall user experience, making them an indispensable tool in Java multithreaded programming.
If you have more experience, such as ten years, these types of java interview questions for 10 years experience
2024 can be asked.
11. Explain the differences between time slicing and preemptive scheduling?
In the case of time slicing, a task executes for a specified time frame – also known as a slice. After that, it enters
the ready queue — a pool of ‘ready’ tasks. The scheduler then picks the next task to be executed based on the
priority and other factors.
Time slicing is useful for non-priority scheduling. Every running- thread would be used for a fixed period. It is used
for a predefined slice of time.
Whereas under preemptive scheduling, the task with the highest priority is executed either until it enters dead or
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 5/42
3/14/24, 1:41 AM (3) New Messages!
e eas u de p ee pt e sc edu g, t e tas t t e g est p o ty s e ecuted e t e u t t e te s dead o
warning states or if another higher priority task comes along.
0:00
The daemon nature of the garbage collector thread allows it to coexist harmoniously with other threads, executing
its crucial role without delaying or obstructing the program’s primary functionality. This non-obtrusive yet essential
thread contributes to Java’s efficiency and robustness, facilitating smoother application execution.
14. State the methods used during deserialization and serialization process.
ObjectInputStream.readObject
Reads the file and deserializes the object.
ObjectOuputStream.writeObject
Serialize the object and write the serialized object to a file.
The volatile variable is casted with a keyword “volatile” to signify that this variable can be changed by some outside
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 6/42
3/14/24, 1:41 AM (3) New Messages!
The volatile variable is casted with a keyword volatile to signify that this variable can be changed by some outside
factor.
It is a field modifier.
Improves thread performance
The thread cannot be blocked for being volatile in case waiting.
Not subject to compiler optimisation.
The disadvantage of this method is that we cannot extend any other classes since the thread class has already
been extended.
● By implementing Runnable interface.
The thread class make performing operations on a thread easier by providing constructors and methods to create.
It also facilitates in extending objects class and implementing runnable interface.
There are no default values assigned to the local variables. They should be declared and the initial value should be
assigned before the first use.
22. What is Singleton in Java?
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 7/42
3/14/24, 1:41 AM (3) New Messages!
at s S g eto Ja a
It is a class with one instance in the whole Java application. For an example java.lang.Runtime is a Singleton
class. The prime objective of Singleton is to control the object creation by keeping the private constructor.
A singleton class can have only one object or instance of a class at a time.
Ensures existence of only class in JVM.
Must provide global access point to get the instance of class.
It is used for caching, logging, drivers object, thread pool, etc.
Java interview questions 2024 can be frequently asked in coming times. So do not restrict yourself to one line
response, rather mention of few features as well.
A static method can be invoked without the need for creating an instance of a class. A static method belongs to the
class rather than an object of a class. A static method can access static data member and can change the value of
it. A static methods are accessed by their class name, rather than object of class.
One significant trait of static methods is their ability to access and modify static data members, promoting efficient
data handling. It differentiates them from instance methods that operate within an object’s scope. Utilizing static
methods enhances code organization and fosters a modular approach, simplifying the design and maintenance of
Java programs by enabling direct class-level interaction.
Exceptions Unusual conditions during the program. This may be due to an incorrect logic written by incorrect user
input or programmer.
This exception event occurs at an execution of a program disrupting the normal flow of the program’s instructions.
There are various types of exceptions in Java such as-
1. Checked exception
2. Unchecked exception
Java is a high-level, platform-independent, object-oriented portal, and offers support with high performance for
building sophisticated programs, applications, and websites. Java is a general-purpose programming language that
empowers developers to build rich functionality applications with their write once run anywhere (WORA)
environment. James Arthur Gosling, a computer scientist from Canada, developed Java in 1991 and is popularly
known as ‘Dr Java’. Today, Java has become an essential foundation for the modern IT industry.
A String Pool in Java is a distinct place that has a pool of strings stored via the Java Heap Memory. Here, String
represents a special class in Java, and string objects can be created using either a new operator or using values in
double-quotes.
The String is immutable in Java, thus, making feasibility of String pool and then the further implementation via
String interning concepts.
27. What is a collection class in Java? List down its methods and interfaces?
Java Collection Classes are special classes, which are exclusively used with static methods that work specifically
on return collections. Java Collection by default inherit a class and have two essential features as:
They support and operate with polymorphic algorithms that return new collections for every specific collection.
Methods in Java Collection throw a NullPointerException in case the class objects or collections have Null
value.
There are more than 60 methods, modifiers, and types of Java Collection classes. Here is a list of the topmost
important methods in Java Collection Class:
1. static <T> boolean addAll() This method allows the addition of specific elements to a particular
collection.
2. static <T> Queue <T> This method allows the listing of the collection as Last-in-first-out
asLifoQueue() (LIFO) in view.
3. static <T> int binarySearch() This method allows searching for a specific object and then returns
them in a sorted list.
4. static <E> Collection<E> This method returns the dynamic view from any particular collection.
5. static <E> List <E> This method gives a return of a dynamic typesafe view from a
particular list.
1 import java.util.*;
2 public class CollectionsExample {
3 public static void main(String a[]){
4 List<Integer> list = new ArrayList<Integer>();
5 list.add(90);
6 list.add(80);
7 list.add(76);
8 list.add(58);
9 list.add(12);
10 System.out.println("Minimum Value element in the collection:
11 "+Collections.min(list));
12 }
Copy }
Code Copy Code
1 import java.util.*;
2 public class CollectionsExample {
3 public static void main(String a[]){
4 List<Integer> list = new ArrayList<Integer>();
5 list.add(90);
6 list.add(80);
7 list.add(76);
8 list.add(58);
9 list.add(12);
10 System.out.println("Maximum Value element in the collection:
11 "+Collections.max(list));
12 }
Copy }
Code Copy Code
M i V l l t i th ll ti 90
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 9/42
3/14/24, 1:41 AM (3) New Messages!
Maximum Value element in the collection: 90
Experienced professionals are expected to have an organised answer for these types of questions. You may
choose to tackle java interview questions for 8 years experience 2024 in this manner.
Servlets are Java software components that add more capabilities to a Java server via technology, API, interface,
class, or any web deployment. Servlets run specifically on Java-powered web application servers and are capable
of handling complex requests from the web server. Servlets add the benefit of higher performance, robustness,
scalability, portability, and ensure safety for the Java applications.
Java Servlets come with multiple classes and interfaces like GenericServlet, ServletRequest, Servlet API,
HttpServlet, ServeResponse, etc.
In Servlet, RequestDispatcher acts as an interface for defining an object to receive requests from clients at one
side and then dispatching it to particular resources on the other side (that may be a servlet, HTML, JSP). This
RequestDispatcher has two methods in general:
void forward(ServletRequest request, That allows and forwards the requests from any servlet to
ServletResponse response) server resources in the form of a Servlet, HTML file, or a JSP
file.
void include(ServletRequest request, That has content for a particular resource in the form of a
ServletResponse response) response such as HTML file, JSP page, or a servlet.
Servlet is a Java software component that has the main function to first take the request, then process the request,
and give a response to the user in an HTML page. Here Servlet Container manages the life-cycle of a servlet. Here
are the main stages:
Loading Servlet.
Then initialising the Servlet.
Handling the Request (invoking service method).
Then destroying the Servlet.
Source
Loading Servlet
The life cycle for Servlet begins with the loading stage in the Servlet container. Servlet loads in either of the two
ways with:
Secondly, this process may get delays, as the container selects the right servlet to handle the request.
Now the containers first load the Servlet class and then build an instance via the no-argument constructor.
Initialising Servlet
Next step is to use the Servlet.init(ServletConfig) method to initialise the Servlet for instance JDBC data source.
Here the Servlet takes the client requests and performs the required operation using the service() method.
Now the Servlet container destroys the servlet by performing and completing specific tasks and calling the
destroy() method in the instance.
Sessions track the user’s activity after they login to the site. Session management provides the mechanism to
procure information for every independent user. Here are the four different methods for session management in the
servlets:
HttpSession
Cookies
URL Rewriting
HTML Hidden field
Java Database Connectivity (JDBC) here acts as a software component that allows Java applications to
communicate with a database.
Connections define the sessions between the database and Java applications. JDBC Connection interface is part
of the java.sql package only and provides session information for a particular database. These represent multiple
SQL statements for executing and results in the context of a single connection interface. Here are the main
methods for Connections interface:
createStatement(): To create a specific statement object for adding SQL statements to the particular database.
setAutoCommit(boolean status): To define the connection of a commit mode to a false or true directive.
commit(): That makes all the modifications from the last commit and further releases any database presently
held by the specific Connection object.
rollback(): That undoes or rollbacks all the changes done in the past or current transaction and also releases
the presently held database in the connection object.
close(): That terminates or closes the current connection and also releases or clears the JDBC resources
instantly.
Web module
Struts module
Servlet module
Core Container module
Aspect-Oriented Programming (AOP)
Application Context module
MVC framework module
JDBC abstraction and DAO module
OXM module
Expression Language module
Transaction module
Java Messaging Service (JMS) module
ORM integration module
Source
35. Explain Bean in Spring and list the different scopes of Spring bean.
Beans are one of the fundamental concepts of the Spring framework in managing structures efficiently. In a simple
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 12/42
3/14/24, 1:41 AM (3) New Messages!
Beans are one of the fundamental concepts of the Spring framework in managing structures efficiently. In a simple
definition, Spring Bean represents the IoC containers that manage the object forming the backbone of applications.
Scopes play a crucial role in the effective use of Spring beans in the application. Scope helps us to understand the
lifecycle of the Spring Bean, and they have the following types.
1. Singleton – By default, Spring bean scope has a singleton scope that represents only one instance for
Spring IOC container. This same object gets shared for each request.
2. Prototype – In this, a new instance will be called and created for every single bean definition, every time a
request is made for a specific bean.
3. Request – In this scope, a single bean will be called and created for every HTTP request for that specific
bean.
4. Session – This scope defines the single bean use for a life cycle in a particular global HTTP session.
5. Global-session – This scope allows a single bean for the particular life cycle for implementing in the global
HTTP session.
Note: Last three scopes are applicable in the web-aware Spring ApplicationContext only.
While configuring XML based Spring MVC configuration in web.xml file, two declarations of DispatcherServlet and
ContextLoaderListener play an essential role in complementing the purpose of the framework.
DispatcherServlet –
DispatcherServlet has the primary purpose for managing incoming web requests for specific matching configured
URI patterns. DispatcherServlet acts as the front controller for the core of the Spring MVC application and
specifically loads the configuration file and then initialises the right beans present in that file. And when annotations
are enabled, then it can also check and scan the configurations and packages for all annotated with @Repository,
@Component, @Service, or @Controller.
ContextLoaderListener –
ContextLoaderListener here acts as the request listener for starting and shutting down root
WebApplicationContext. So, it creates and shares the root application context with child contexts by the
DispatcherServlet contexts. Applications can only use one entry for the ContextLoaderListener in the web.xml.
Hibernate defines a layered architecture that empowers users to operate and perform without knowing the
underlying APIs, i.e., Hibernate acts as a framework to build and develop persistence logic independent from the
Database software.
There are several aspects and scope for Hibernate architecture. To learn more about them, you must know about
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 13/42
3/14/24, 1:41 AM (3) New Messages!
e e a e se e a aspects a d scope o be ate a c tectu e o ea o e about t e , you ust o about
the elements of Hibernate architecture.
SessionFactory: Sessionfactory provides the method to create session objects that are present in the
org.hiberate package only. It is thread-safe in nature, immutable, and holds and preserves the second-level
cache of the data.
Session: Session objects provide the interface for Connection and Database software via the hibernate
framework.
Transaction: Interface that aids transaction management and allows a change in the database.
ConnectiveProvider: A part of the JDBC connections, it separates the main application from the DataSource or
DriverManager.
TransactionFactory: Represents the factory of the transaction.
The exception defines the unwanted events that present themselves during the run or execution of the program.
Exception disrupts the regular flow of the program.
Exception Hierarchy is part of the java.lang.Exception class and comes under the primary Throwable class only.
Another subclass ‘Error’ also represents the Throwable class in Java. Though Errors are unusual conditions in
case of a failure, still they are not handled or cleared with the Java programs.
There are two primary subclasses for exceptional hierarchy in Java with RuntimeException class and
IOCException Class.
This unwanted or unexpected event can occur at several times such as compile-time or run- time in an application.
Synchronization in Java defines the capability to manage and control the access of multiple threads to a particular
resource. So that, one thread can access a specific resource at the present time. Here, Java allows the
development of threads and then synchronizing tasks via the synchronizing blocks.
These Synchronized blocks allow only one thread execution for a particular time and block the other threads until
the current thread exits in the block. Here monitors concept is crucial in implementing the synchronization in Java.
Once the thread goes in a lock phase, it is termed to enter the monitor. Thus, locking all the other threads unless
the first thread has exited the monitor.
Synchronization gives the capability to control multiple threads at any resource that is shared. Synchronization
becomes usefu for reliable communication between threads as the multiple threads might try to access the shared
resources at the same time thus producing results that are inconsistent.
40. What are the features that make Java one of the best programming languages?
Here are the top features that make Java for starting your learning curve in the programming world:
Simplicity: Java is quite simple to learn and write. Java syntax is in C++ that allows the developers to write
programs seamlessly.
OOPS: Java is based on the object-oriented programming system (OOPS), thus, empowering to build code in
multiple types of objects with different data and behavior.
Dynamic: Java is a complete dynamic language that supports the loading of dynamic classes whenever and
wherever required. And it also has comprehensive support for native code language such as C, C++, etc.
Platform Independent: Java also supports exclusive and platform-independent programming language, thus,
allowing developers to run their program on their platform only.
Portability: Java has a reach once write anywhere approach that allows the code to run on any platform.
Security: Following the concept of ByteCode, exception handling, and no use of any explicit pointers makes
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 14/42
3/14/24, 1:41 AM (3) New Messages!
Secu ty o o g t e co cept o yteCode, e cept o a d g, a d o use o a y e p c t po te s a es
Java a highly secured environment.
Java is also architect neutral with no dependency on any architecture. Strong memory management and
automated garbage collection add more robustness to its environment.
Use of Just in Time (JIT) compiler in its architecture makes Java one of the high performing programming
languages, as it transforms instructions into bytecodes.
The JIT compiler is helpful in compiling of code on demand. The fast and time efficient features come into play
because whichever method is called, only that method block gets compiled.
There are many IDE’s available in the industry for Java. Here are the top five Java IDEs that you can use to start
learning this programming language today:
Eclipse
Netbeans
IntelliJ
JDeveloper
MyEclipse
43. Define the main differences between Java and other platforms?
Two main differences that make Java stand out from other platforms are:
Java is primarily a software-based platform, while others can be either software or hardware-based platforms.
Java runs or executes on any hardware platform, whereas others require specific hardware requirements.
You may refer to the below mentioned table to understand the differences between Java and other platforms-
Software-only platform that runs on top of hardware- based Other platforms are usually hardware
platforms. software or hardware only platforms.
Java code can be developed n any OS. Other platforms do not have this feature.
Java has its own run time environment such as JRE(Java Run- This function is missing on other platforms.
Time Environment) and JVM (Java Virtual Machine)
44. What makes Java have its ‘write once and run anywhere’ (WORA) nature?
Well, the one-word answer is Bytecode. Java compiler converts all the Java programs into a specific Byte Code
acting as a mediator language between the machine code and source code. ByteCode can run on any computer
and has no platform dependency.
In the Java programming language, access specifiers represent the exact scope for class, variable, or a method.
There are four main access specifiers:
Public defined variables, methods, or classes are accessible across any method or class.
Protected access specifier defines the scope of a class, method, and variable to the same package, within the
same class, or to that particular subclass of class.
The Default scope is there for all the present classes, variables, and methods with access to the package only.
The Private scope keeps access of class, variables, and methods to a particular class only.
The access modifiers are mainly used for encapsulation. It helps to control what part of program can access the
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 15/42
3/14/24, 1:41 AM (3) New Messages!
The access modifiers are mainly used for encapsulation. It helps to control what part of program can access the
members of a class to prevent the data misuse.
While tackling questions like such make sure to also make a slight mention of importance of access modifiers. It
gives an edge during java interview questions and answers for freshers.
46. Explain the meaning of packages in Java along with their advantages.
Packages are a grouping mechanism for similar types (interface, classes, annotations, and enumerations) ensuring
the protection of the assets and comprehensive name management.
The packages are used to categorise the classes and interfaces. The categorisation is done for smoother
maintenance. The packages are also useful for providing protection.
Packages help us prevent naming conflicts when classes of the same name exist in two different packages.
Packages aid in making access control systematically.
Build hidden classes to be used by the packages.
Helps in locating related classes for the package.
Provides access protection.
Reuse classes
Provide controlled access
Implement data encapsulation
Easy search
Constructors are a special block of codes that initialises an object in the time of creation. Though it has a
resemblance to instance method, still Constructors are not the method, as they don’t have any explicit return type.
So every time an object is being created in the system, there is one constructor called for that to execute. If there is
no constructor defined, then the compiler uses a default constructor.
Default Constructor: When a developer doesn’t use a constructor, Java compiler adds a more specific default
constructor existing in the .class file.
No-argument Constructor: In this case, there are no arguments in the constructor and the compiler doesn’t
accept any parameter, as instance variable method gets initialised with specific fixed values.
Parameterized Constructor: In this case, one or more parameters are present in the constructor written inside
the parentheses of the main element only.
Purpose: Constructors aim is to initialize the object of a class whereas method performs specific tasks on code
execution.
The method has return types while constructors do not.
In Methods, there are abstract, static, final, and synchronization while in constructors, you can’t make specific
procedures.
You may refer to the below mentioned table for differences-
Constructors Methods
Gets executed only when object is created. Can be executed on beng explicitly called.
Name is same as the class name. Name will not be same as the class name.
Local variables are present in the method, and the scope exists within the method only.
Instance variables are present and defined in the class only with their scope across the class.
In Java, all the codes, variables, and methods are defined in the class.
Objects are defined as an instance of a class only with specific state and behavior. For example, a dog with a
specific state of name, breed, and colour while behavior includes barking, wagging the tail, etc. So anytime JVM
reads any new() keyword then a corresponding instance will be created. An object needs to be first declared, then
instantiated and finally initialized for performing further. Each object has its own identity, behavior and state. The
state is stored in fields (variables), methods (functions) showcase the objects behavior.
53. Define the default value for byte datatype in Java language.
As byte data type is almost four times smaller than an integer, so it can store more space for large arrays.
They can also be used in place of int, where their limits help to clarify the code.
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 17/42
3/14/24, 1:41 AM (3) New Messages!
They can also be used in place of int, where their limits help to clarify the code.
OOPs, are the fundamental concepts of the Java programming language. These include abstraction,
polymorphism, inheritance, and encapsulation. Java OOPs concepts empower developers to create variables,
methods, and components that further allow them to reuse them in a customised way while maintaining security.
Abstraction- This is useful for hiding internal details. It is also useful to show functionality.
Polymorphism- It is when an object behaves differently in different situations. There are two types of
polymorphism run-time and compile-time polymorphism.
Inheritance- It is when an object acquires the properties and behaviours of another object. The object whose
quality gets inherited is called a superclass. The object inheriting the properties is called a sub-class.
Encapsulation- It is used for binding/ wrapping a code and data together in a unit. Access modifier keywords are
also used in this process.
In Java, Inheritance is a specific mechanism that allows one class to acquire the properties (with fields and
methods) of another class. Inheritance is one of the basic concepts of Java OOPs.
Inheritance makes it possible to build new classes, add more fields and methods on the existing classes for reusing
them in any way.
A subclass is the one that inherits the properties of the other class.
Superclass is the one whose properties are inherited.
Some of the properties of inheritance include-
Allows to create of a new class from the existing class.
The object acquires all the properties of the object it is inheriting from.
The methods can be reused of the superclass.
New methods and fields can be added to the current class.
Inheritance in java can be used for method overriding.
As one of the primary concepts of Java OOPs, Encapsulation empowers the wrapping of data and code within a
single unit only. Encapsulation is also known as Data hiding, with variables of a specific class hidden from all other
classes and accessible with the methods from the existing class only.
Polymorphism in Java allows developers to perform a single task in multiple ways. There are two types of
Polymorphism in Java with Runtime and Compile time. You can use overriding and overloading methods to operate
Polymorphism in Java.
In Java, we cannot achieve multiple inheritances. Here, interface plays a crucial role in overcoming this problem to
achieve abstraction, aid multiple inheritances, and also supports loose coupling. Now we have a default, static, and
private method in interface with the latest Java updates.
Benefits of interface-
Abstract classes are built with a specific abstract keyword in Java. They represent both abstract and non-abstract
methods.
Abstraction is one of the essential properties for hiding the implementation information from the user and then
representing the user functions only. For instance, when you send an SMS from one person to another person. The
user gets to know only the message and number while the backend process remains hidden.
You can achieve abstraction in Java using the following two ways:
Abstraction Encapsulation
In the abstraction process, issues or problems are handled In Encapsulation, problems are handled at a specific
at the interface/ design level. implementation level.
Abstraction aids in hiding unwanted information. Encapsulation method applies hiding data within a
single unit.
Implemented with interfaces and abstract classes. Implemented with a particular access modifier
(public, private, and protected).
Use abstract classes and interfaces to hide complexities. Use getters and setters to hide data.
Objects that extend to abstraction must be encapsulated. An object for encapsulation must not be abstracted.
Abstract Class comes with a default constructor The interface doesn’t have a constructor So no
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 19/42
3/14/24, 1:41 AM (3) New Messages!
Abstract Class comes with a default constructor. The interface doesn’t have a constructor. So, no
further process.
Uses both Abstract and Non-Abstract methods. Only use Abstract methods.
Classes that must extend for Abstract class need only Classes that extend to interface must provide
abstract methods throughout their sub-class. implementation across all the methods.
64. Explain the main differences between Array and Array List.
The size needs to be defined for the declaring array. No size requirements; and modifies dynamically.
String[] name = new String[5] ArrayList name = new ArrayList
You must specify an index for putting an object There are no index requirements.
inside the array.
name[1] = “dog”
name.add(“dog”)
Arrays are not parameterised. From Java 5.0 onwards, ArrayLists have a specific
parameterised type.
65. Explain the difference between static method and instance method.
You must declare a method static for a static method. All methods with declaration as static come under
Instance method only.
No requirements for creating objects in the Static The object is a must for calling the instance method.
method.
You cannot access Instance or Non-static methods in You can access both static and non-static in the
the static context. instance method.
Status methods are used to perform a single operation. Instance methods are used to perform repetitive
operations.
The static must be accessed with a repetitive class The instance method must be accessed with a repetitive
name. object name.
They are alternatively called Class Level Data They are alternatively called Object Level Data
Members. Members.
Constructors invoked with the object, and static context is part of the class, not the object. Hence, constructors
cannot be static and show compiler error if run or executed.
Why Learn to Code? How Learn How to Install Specific Version of Types of Inheritance in C++ What
to Code? NPM Package? Should You Know?
In Java, ‘this’ keyword represents a specific reference on the current object. There are multiple uses for this
keyword for referring to the current class properties from a variable, constructors, methods, and more. You can also
pass this as an argument within constructors or methods. You can also fetch this as a return value from the current
class instance. You can also refer to this as a static context.
68. What is a classloader in Java? What are the different types of ClassLoaders in Java?
Java Classloader’s main function is to dynamically load all classes into the Java Virtual Machine (JVM).
ClassLoaders are part of the JRE only. So every time we run a Java program, classloader loads the classes to
execute this program. A single ClassLoader loads only a specific class on requirements and uses getClassLoader()
method to specify the class. These classes are loaded by calling their names, and in case these are not found then
it retrieves or throws a ClassNotFoundException or NoClassDefFoundError.
Java ClassLoader uses three principles in performing tasks with delegation, uniqueness, and visibility.
There are three different types of Java ClassLoader:
BootStrap ClassLoader:
BootStrap ClassLoader represents the parent or superclass for extension classloader and all other classloaders. It
has machine code that loads the pure first Java ClassLoader and takes classes from the rt.jar and also known as
Primordial ClassLoader.
Extension ClassLoader:
Extension ClassLoader represents the child classloader for the superclass or BootStrap ClassLoader. It loads core
java classes from jre/lib/ext, i.e., JDK extension library.
System ClassLoader:
Application or System ClassLoader are further child classes of Extension ClassLoader. It takes and loads a file
from the current directory for the program that you can customise with the ‘classpath’ switch.
Java Applet is a program that executes or runs in the web browser only. Applets are specifically designed to
function and embed with HTML web pages. Applets have the capability to function full Java applications with the
entire use of Java API. JVM is a must requirement to view an applet on the browser. Applet extends with the use of
java.applet.Applet class.
Based on location, there are two types of Java applets as Local Applets that are stored on the same computer or
system. The Remote Applets that have files on remote systems.
In Java, immutable objects are the ones whose state does not change after it has been created. Immutable objects
are ideal for multi-threaded applications that allow sharing the threads while avoiding synchronization. Immutable
objects are preferred for building simple, sound and reliable code to match with an effective strategy.
Safety of threads
Prevention of identity mutation.
Brings ease of caching
Supports referential transparency
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 21/42
3/14/24, 1:41 AM (3) New Messages!
Supports referential transparency
Protection from the corruption of existing objects
Java Runtime Environment is the software layer that provides support for minimum requirements to run Java
programs on a machine. Along with JDK and JRE, these three constitute the fundamental for running and
developing Java programs on a specific machine.
Java Development Kit (JDK) is one of the primary technology packages essential for running Java programs. It can
be the implementation from any one of the Java platforms, Standard Edition, Micro or Enterprise edition developed
by Oracle for building applications on Windows, Linux, or macOS.
Java Virtual Machine (JVM) is one of the three fundamental requirements for running and executing Java programs
along with JDK and JRE. JVM has two primary functions; first, to empower Java programs to seamlessly run on
any machine or system and second to optimise memory to deliver performance.
Code compatability.
The application can be run anywhere, as it supports (Write Once Run Anywhere).
Garabage Collection
Compile Control
Supports Native Memory Tracking
Facilitates Class Data Sharing
Helps in Signal Chaining
Platform dependent with several Software layer that provides support Standard Edition
software and hardware options for minimum requirements to run Java Enterprise Edition
available. programs on a machine. Micro Edition
Three notions as: Set of libraries + files that empower JRE + development tools
JVM on runtime.
Specification
Implementation
Instance
Provides runtime environment for JRE represents the implementation of Software development environment.
execution. JVM.
Class Area: This memory stores pre-class structures with the field, pool, method data, and code.
Heap stands for runtime memory specifically allocated to the objects.
Stack represents the frame’s memory with a local variable, partial results, thread, and a frame for each method.
Program Counter Register stores the information for current instruction with the Java Virtual machine execution.
Native method Stack stores all the present native methods being used in the current applications.
Data binding represents the connections between class and method, field, variable, constructors, or a method
body. Java can handle data binding both statically and dynamically.
Static Binding happens at compile time using static, final, and private methods; also known as early binding.
Dynamic Binding presents at runtime with no exact information known about the right method during the compile
time.
Refer to the below table for static and dynamic binding difference-
Can take place using normal functions. Can take place using virtual functions.
Sockets help in building communication mechanisms from the two computers via TCP. Sockets are ideally more
sufficient and flexible for communications.
A java socket point facilitates two-way communication link between two points.
It is bound to a port number for the TCP layer to identify the application.
Establish a connection between a client and a server.
Both path and Classpath represent local environment variables. The path provides the software to locate the
executable files while ClassPath specifies the location for .class files in the system.
Refer to the below mentioned table to undesratnd the differences between these two-
Path Classpath
Environment variable is used by the operating system to Environment variable is used by rhe Java Compiler to
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 23/42
3/14/24, 1:41 AM (3) New Messages!
Environment variable is used by the operating system to Environment variable is used by rhe Java Compiler to
find the executable files. find the path classes.
It is used by CMD prompt in order to find files that are It is used by compiler and JVMto find files that are
binary. binary.
We must place .\bin folder path We must place .\lib\jar file or directory path
In Java, you can make a read-only class by keeping all the fields private. This specific read-only class will have
only getter methods that return private property. It does not allow to modify or change this property as no setter
method is available.
In Java, you can also make a write-only class by keeping all the fields private with the implementation of setter
methods only.
In Java, there are two ways to access a class in another class as:
Using the specific name: We can access a particular class from a different package by using the qualified
name or import that package that contains a specific class.
Using the relative path: Similarly, we can also use the relative path for that package with a specific class.
Exception handling represents the mechanism to handle the exception or abnormal conditions during the runtime
errors to keep the normal flow of the application. There are three different types of Java Exceptions with Checked
Exception, Unchecked Exception, and Error.
It is a process of responding to unwanted or unexpected events that happens when a computer program runs.
Helps to avoid system crashing by handling with events.
It is a mechanism that allows Java programs to tackle various situations.
There are various ways an exception can be handled such as-
Throwing an exception
Catching an exception
Handling an exception
86. Explain the difference between Checked Exception and Unchecked Exception.
Checked Exceptions are classes that further extend throwable classes except for RuntimeException such as
SQLException, IOException, etc. Checked Exceptions are handled during the compile-time only.
Occurs when the chances of failure are too high. Occurs due to programming misfunctionality.
Not sub class of run time exception. Sub class of run time exception.
Here, the Throwable class represents the base class for Exception and Error.
Keyword Description
try This try block defines the block for placing the execution code. This try block is
generally followed by the use of either catch or finally. So, they can’t be used alone.
catch Catch block’s main aim is to handle the exception. You must use this in combination
with try block and then finally in the later stage.
finally Finally, block checks the important code of the program that checks whether execution
is done or not.
throw The main aim of the throw keyword is to throw an exception from the program.
throws The throws keyword is mainly used for declaring exceptions and not for throwing an
exception. It provides information about occurrence for exception and is applied with a
method signature.
Here, the finally block has crucial importance in the smooth running of the program. It is always executed whether
the exception is handled or not. Finally, the block comes after the try or catch block. In the JVM, the system will
always run the finally block before terminating or closing a file. For each try block present, there can be zero or
multiple catch blocks, still there can only one finally block.
Yes, a finally block can run followed by either a try or catch block, respectively.
91. Are there any cases for not existing finally block?
Finally block does not run or execute in case the program already exists or brings fatal error for aborting the
process.
Checked exceptions can’t propagate with Checked exceptions can propagate with
throw only. throws.
There are no possibilities for multiple Whereas in this procedure, multiple exceptions
exceptions. can be declared.
The process of exception within the handling procedure is known as exception propagation. For instance, an
exception is first handled at the top of the stack and then if it is not caught then the exception drops to the previous
method and if not, then it goes down further till either the exception gets caught, or it reaches the bottom of the
stack. Checked exceptions by default have no propagation.
In Java, the way or flow of the execution is known as the thread. So, every program contains one thread termed as
the main thread created by the JVM. Developers have the power to define their custom threads by adding and
extending the Thread class using the interface.
Java thread pool is a group of multiple threads that are continuously waiting for allocated tasks. Here Thread pools
work under the service provider that pulls a thread from this pool and then assign them the task for a specific job.
The Thread pool adds more performance and stability to the system.
String StringBuffer
These consume more memory for creating a These consume less memory with concat
new instance. strings.
Strings allow the comparison of its content, Whereas the StringBuffer class cannot
as it overrides the equals() method from the override the equals() method from the Object
Object class. class.
StringBuffer StringBuilder
In this, two threads have no call method. In this, two threads can have call methods seamlessly.
In Java, you can create an immutable class by declaring a final class with all its members as final. Let’s take an
example to understand this:
Java Inner classes are defined and declared within an interface or class. Inner classes allow the system to group
classes and interfaces logically making them more readable as well as easy to maintain them. Moreover, these
classes can access all members of the outer class with methods as well as private data members.
100. What are the main advantages and disadvantages of using Java Inner classes?
101. Define the types of inner classes in the Java programming language?
Member Inner class that specifies a class within the class using the outside method.
Anonymous Inner Class for extending the class or specifying the implementation of an interface.
Local Inner Class to create a class within the method.
Nested classes are defined or declared within a class or interface only. A nested class can specifically access all
the members of the outer class with methods and private data members too. Here is a simple syntax of a nested
class:
1 class Java_Outer_class{
2 //code
3 class Java_Nested_class{
4 //code
5 }
6 }
Copy Code Copy Code
103. Can you explain the difference between inner classes and nested classes?
All inner classes are defined as non-static nested classes. So, inner classes are part of the nested classes only.
You may refer to the below mentioned table to understand the difference-
Always associated with the outer class object. Not associated with the outer class object.
Normally main() method cannot be declared. The Main() method can be declared.
Static and Non Static members of the outer class can be Static members of the outer class can be directly
directly accessed. accessed.
Collections in Java are a group of multiple objects that present as one unit; primarily known as a Collections of the
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 28/42
3/14/24, 1:41 AM (3) New Messages!
Co ect o s Ja a a e a g oup o u t p e objects t at p ese t as o e u t; p a y o as a Co ect o s o t e
objects. They are also called a Collection Framework or architecture that provides storing space for objects and
further manipulates design for changes.
Sorting
Searching
Insertion
Manipulation
Deletion
There are many interfaces and classes that are part of the collections.
Here is the list of the interfaces and classes that are available with the collections in Java.
Interfaces: Collection, Queue, Sorted Set, Sorted Map, List, Set, Map
Classes: Lists, Vector, Array List, Linked List
Sets: Hash set, Tree set, Linked Hash Set
Maps: Hash map, Hash Table, TreeMap, Linked Hashed Map
Queue: Priority Queue
Sorted: Sorting allows the group of objects to apply internally or externally to sort them in a particular collection,
based on their different properties.
Ordered: Defines the values that are sorted on the basis of the values added in the collection and iterate them in
a particular order.
Lists store values based on their index position with the duplication allowed. Here are the main types of lists:
Array Lists: Uses the Random Access Interface, provides order collection by the index, not sorted, and offers
quick iteration. Here is an example to understand this:
Output is as follows:
With the output, you can check that Array List keeps the original insertion order and also allows duplicates. Though
not sorted.
Vector: also uses the Random-access method, are synchronised, and offers support for thread safety.
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 29/42
3/14/24, 1:41 AM (3) New Messages!
ecto a so uses t e a do access et od, a e sy c o sed, a d o e s suppo t o t ead sa ety
Output is as follows:
Vector lists follow the original insertion order and also support the duplicates.
Linked List: It is also an ideal choice for deletion and insertion, elements are double-linked, but is slow in
performance.
Output is as follows:
108. What are the main differences between collection and collections in Java?
Priority Queue defines the queue interface for handling linked lists with the purpose of a Priority-in and Priority-out.
Queue generally follows a first in first out (FIFO) algorithm, still you can queue elements based on specific
requirements, and then we can implement PriorityQueue for customisation. With Priority Queue, it depends on the
priority heap either naturally or via the comparator on their relative priority.
110. When is it ideal to use and compare the Runnable interface in Java?
When we need to extend a class with some other classes and not the threads then runnable interfaces are an ideal
choice.
111. What is the difference between start() and run() method of thread class?
The start() method adds and creates a new thread. And code in run() method gets executed in the new thread only.
While run() method will execute code in the current thread only.
In Java, we can execute multiple threads simultaneously, which is known as Multithreading. It helps the program to
multitask while taking less memory and giving higher performance. In Multithreading, threads are lightweight, share
the same space, and are quite affordable in every aspect.
A Java program in execution is termed as a process while a thread represents a subset of the process only.
Processes represent different spaces in the memory, while threads have the same address.
Processes are entirely independent, while threads are part of the process only.
Slow communication between inter-processes, while the inter-thread communication is swift.
Process Threads
Allocate new resources each time a program is run. Share resources of process.
Inter-thread communication is defined as the process that allows communication between multiple synchronised
threads. Its main aim is to avoid thread pooling in Java. Communication is achieved through the methods of wait(),
With wait() method, you can allow the thread to be in the waiting stage while the other thread is locked on the
object. Thus, the wait() method can add significant waiting duration for threads.
116. What is the main difference between the notify() and notifyAll() method in Java?
notify() method sends a signal to wake up only a particular thread in the waiting pool whereas notifyAll() wakes up
all the threads in the waiting stage of the pool.
Sleep() pauses or stops the current thread progress by suspending execution for a particular duration while not
releasing the lock. While wait() causes a waiting duration for a thread after invoking a notify() method for waking
later.
sleep() wait()
The join() method allows combining one thread with one of the continuous threads. Here is a syntax for join()
method:
Yield method is a static method and does not release any lock in the threads. Here, a Yield() method empowers the
current thread to a more runnable thread while allowing the other threads for keeping the execution. Thus, equal
thread priority threads can run regularly.
Starvation is a phase when a thread fails to gain access to shared resources and is not able to make any
progress.
It is when the thread is not able to gain regular access to the shared resources.
When shared resources are made unavailable for long periods.
Deadlock defines a stage when two or multiple threads get blocked forever in wait for each other.
Serialisation is the process for transforming the state of an object into a particular byte stream ideally suited for
JPA, JMS, RMI, JPA, and Hibernate technologies. While the opposite process of changing a byte stream into an
object is called deserialisation. Both processes are platform-independent, so they allow you to serialise in one
platform and deserialise into an entirely different platform efficiently.
The importance of transient variables lies in the deserialisation that is set to the default variables and not used with
the static variables.
Volatile variables play a crucial role in the synchronisation and reading from the main memory while avoiding the
thread cache memory.
In the Serialised process, an object is stamped with a specific version ID number for the respective object class.
This number is termed as SerialVersionUID and plays a crucial role in verifying during the deserialisation process
for checking the compatibility on sender and receiver, respectively.
With Object cloning, you can create an exact copy of the original object. For cloning to be possible, a class must
have the support for cloning with the java.lang.Cloneable interface and allow override clone() method from the
original object class.
In case the clone does not implement it then it generally throws an exception with the
‘CloneNotSupportedException’.
127. Define the class that remains superclass for each class?
Object class.
String class represents an immutable state. So once an object is created, this cannot change any further.
In Java, toString() retrieves or returns the string representation from any object.
As objects get dynamically allocated via the operator, Java system also handles the deallocation of the memory
used automatically in case there are no references for the object that remains for a significant duration. This
process of keeping the system free of objects that don’t have use is known as Garbage Collection in Java. The
main aim of the garbage collection is to make it more memory efficient management.
132. What is the number of times a garbage collector calls finalize() method for a specific object?
You can call the finalize() method in garbage collection only once.
System.gc()
Runtime.getRuntime().gc()
No, this is an automatic process. You can call the garbage collection method but can’t force it. Still, it does not
guarantee that it would be complete.
byte – 8 bit
short – 16 bit
char – 16 bit Unicode
int – 32 bit (whole number)
float – 32 bit (real number)
long – 64 bit (Single precision)
double – 64 bit (double precision)
Unicodes are a way to define international characters in human languages, and Java uses this Unicode structure to
symbolise the characters.
In the case of assigning a value of one data type to another data type, these two may or may not be compatible
and require conversion. Java will automatically convert in case of compatible data types. While if the data types are
not compatible, then these must be cast for successful conversion. Casting has two basic types: Implicit and
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 34/42
3/14/24, 1:41 AM (3) New Messages!
ot co pat b e, t e t ese ust be cast o success u co e so Cast g as t o bas c types p cta d
Explicit.
Implicit: Defines the storing of values from smaller data types into larger data types, performed by the compiler
only.
Explicit: Defines the storing of values from larger data types into smaller data types that may result in
information loss.
Conclusion
The above Java interview questions will provide a good start for preparing for the interview. Practice your coding
skills, too, though, and make sure to be thorough in these questions and their related concepts so that when the
interviewer fires a Q, you are ready to win the round with your A. Oh, and don’t forget 3 (inconspicuous) breaths
when you present yourself before the interviewer.
If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-
B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is
designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B
Alumni status, practical hands-on capstone projects & job assistance with top firms.
Arjun Mathur
Blog Author
Arjun is Program marketing manager at UpGrad for the Software development program. Prior to UpGrad, he was a part of the French ride-sharing unicorn "BlaBlaCar" in
India. He is a B.Tech in Computers Science from IIT Delhi and loves writing about technology.
Besides technical Java interview questions, you should also focus on questions based on soft skills such as mentioning your strengths and
weaknesses, the reason for working in this field, leadership skills and more. You should also develop independent projects as they will
provide practical experience. You could develop mobile applications, web applications, and coding projects. The interview not only looks at
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 35/42
3/14/24, 1:41 AM (3) New Messages!
your technical skills and the ability to code but also your overall personality as the companies are finding the perfect fit for the position. They
can ask about your hobbies and extracurricular activities too.
There are several ways you can learn Java such as YouTube videos, online courses, college, and more. You should begin with the basic
syntax of Java programming after which you need to practice with what you have learned. There are hundreds of sites which offer free
problems for people to solve using Java. This would help you apply your knowledge and learn how Java is used in real life. After learning
Java remember to keep up to date with all the new features or technologies.
Java is an object-oriented language as everything present in it is an object and it can be easily extended. Java is a platform-independent
language, as when it is compiled, it doesn't need to be compiled into platform-specific machines, rather it is compiled into platform-
independent bytecode. Java is a simple and secure programming language as it is easy to learn and its features allow it to develop a virus-
free software or application. As Java is architectural neutral it allows Java to be portable. It is also robust as it avoids any error-prone
situations.
The four key concepts in java include- a) Encapsulation b) Inheritance c) Polymorphism d) Abstraction
One of the tools that are really good for java include- Spring JUnit NetBeans Maven Jenkins
Some of the top companies that use Java include- Wikipedia Google Uber Google Earth Netflix
The OOPs concert in Java enhances the code reusability and readability through the process of defining the Java program.
A class is an object constructor. It can also be called a blueprint for creating an object. A class is a category and the objects are the items
within each category.
BESTSELLER P
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 36/42
3/14/24, 1:41 AM (3) New Messages!
Advance your career in the field of marketing Build your foundation in one of the ho
with Industry relevant free courses industry of the 21st century
SUGGESTED BLOGS
5030
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More
5002
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 37/42
3/14/24, 1:41 AM (3) New Messages!
Introduction The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More
5003
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More
5003
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More
file:///C:/Users/ABHISHEK/OneDrive/Pictures/Upgrade.mhtml 38/42