100 Most Asked Java Interview QnA
100 Most Asked Java Interview QnA
100 Most Asked Java Interview QnA
1. What is Java?
Java and JavaScript are two different programming languages with different purposes.
Java is used for building applications, while JavaScript is primarily used for adding
interactivity to web pages.
Java follows the principle of "write once, run anywhere" (WORA), which means that Java
code can be compiled into bytecode and executed on any platform that has a Java
Virtual Machine (JVM).
In Java, a class is a blueprint or template for creating objects. It defines the properties
(attributes) and behaviors (methods) that objects of that class can have.
A method in Java is a block of code that performs a specific task. It can be called or
invoked to execute its defined functionality.
Inheritance is a mechanism in Java where a class can inherit properties and behaviors
from another class. It allows for code reuse and creating a hierarchical relationship
between classes.
Java supports single inheritance, where a class can inherit from only one superclass, and
multiple inheritance through interfaces, where a class can implement multiple
interfaces.
Polymorphism is the ability of an object to take on many forms. In Java, it allows objects
of different classes to be treated as objects of a common superclass, enabling code
flexibility and reusability.
Java provides four access modifiers: public, private, protected, and default (no modifier).
They control the visibility and accessibility of classes, methods, and variables.
Encapsulation is the process of hiding internal details and providing a public interface to
interact with an object. It helps in achieving data abstraction and protects data from
unauthorized access.
The JVM is a crucial part of the Java platform. It is responsible for executing Java
bytecode and provides a runtime environment in which Java programs can run on any
hardware or operating system.
The JDK is a software development kit provided by Oracle, which includes the necessary
tools and libraries to develop, compile, and run Java programs. It consists of the JVM,
compiler, and other utilities.
18. What is the difference between the JDK and the JRE?
The JDK (Java Development Kit) is a software development kit that includes the tools
needed to develop Java applications, while the JRE (Java Runtime Environment) is a
runtime environment required to run Java applications.
An abstract class can have both abstract and non-abstract methods and can be
extended by other classes, while an interface only contains abstract method
declarations and can be implemented by classes.
21. What is a static method in Java?
A static method in Java is a method that belongs to the class rather than an instance of
the class. It can be called without creating an object of the class.
The "final" keyword in Java can be used to declare a variable, a method, or a class. A final
variable cannot be changed, a final method cannot be overridden, and a final class
cannot be inherited.
Method overloading is the ability to define multiple methods with the same name but
different parameters in the same class. The appropriate method is called based on the
arguments passed.
25. What is the difference between method overloading and method overriding?
Method overloading involves defining multiple methods with the same name but
different parameters in the same class, while method overriding involves providing a
different implementation of a method in a subclass that is already defined in its
superclass.
The "this" keyword in Java refers to the current instance of a class. It can be used to
access instance variables, call instance methods, or invoke constructors.
A static variable in Java is a variable that belongs to the class rather than an instance of
the class. It is shared among all instances of the class.
The "static" keyword in Java is used to declare variables, methods, and nested classes
that belong to the class itself, rather than instances of the class. It allows accessing them
without creating an object of the class.
The "==" operator in Java is used to compare the equality of object references, while the
".equals()" method is used to compare the equality of object values. The ".equals()"
method can be overridden to provide custom equality comparison.
The "super" keyword in Java is used to refer to the superclass of a class. It can be used to
access superclass members, invoke superclass constructors, or differentiate between
superclass and subclass members with the same name.
To create and start a thread in Java, you can either extend the "Thread" class and
override the "run()" method, or implement the "Runnable" interface and pass it to a new
"Thread" object. Then call the "start()" method on the thread object to begin execution.
35. What is the difference between the "synchronized" block and the "synchronized"
method?
A "synchronized" block in Java allows a specific block of code to be synchronized,
ensuring that only one thread can execute it at a time. A "synchronized" method applies
synchronization to the entire method, making it mutually exclusive for all threads.
The "volatile" keyword in Java is used to indicate that a variable's value may be modified
by multiple threads. It ensures that any read or write operation on the variable is directly
performed on the main memory, rather than relying on CPU caches.
An exception in Java is an event that occurs during the execution of a program, which
disrupts the normal flow of instructions. It represents an error condition or an exceptional
circumstance.
Exceptions in Java can be handled using try-catch blocks. The code that may throw an
exception is placed inside the try block, and if an exception occurs, it is caught and
handled in the catch block.
The "finally" block in Java is used to define a block of code that will be executed
regardless of whether an exception occurs or not. It is often used to release resources or
perform cleanup operations.
41. What is the difference between the "throw" and "throws" keywords in Java?
The "throw" keyword in Java is used to manually throw an exception, while the "throws"
keyword is used in method declarations to specify that the method may throw certain
types of exceptions.
42. What is the difference between checked exceptions and runtime exceptions?
An ArrayList is implemented as a resizable array, allowing fast random access but slower
insertion and removal of elements. A LinkedList is implemented as a doubly-linked list,
allowing fast insertion and removal but slower random access.
A HashSet in Java stores elements in no particular order, using a hash table for fast
access but does not maintain any specific order. A TreeSet stores elements in sorted
order and allows for efficient retrieval of elements based on their natural ordering or a
custom comparator.
46. What is the difference between the "equals()" method and the "hashCode()"
method?
The "equals()" method is used to compare the equality of objects based on their values,
while the "hashCode()" method is used to calculate a unique hash code value for an
object, typically used for efficient retrieval in hash-based data structures like HashMaps.
47. What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new object that shares the same references as the original
object, while a deep copy creates a new object and recursively copies all the referenced
objects as well, resulting in separate copies.
An interface in Java can only declare method signatures and constants but cannot
provide implementations, while an abstract class can have both method declarations
and concrete implementations. A class can implement multiple interfaces but can
inherit from only one abstract class.
The "default" keyword in Java interfaces is used to define a default implementation for a
method. It allows adding new methods to existing interfaces without breaking the
implementations of classes that implement those interfaces.
A BufferedReader in Java reads text from a character stream with efficient buffering,
while a Scanner can parse different types of data from various sources such as files,
strings, or standard input.
The "StringBuilder" class in Java is used to create and manipulate mutable sequences of
characters. It is more efficient than concatenating strings using the "+" operator, as it
avoids unnecessary object creations.
55. What is the difference between the "Comparable" and "Comparator" interfaces?
The "assert" keyword in Java is used to perform assertions, which are checks placed in
the code to verify specific conditions. It is primarily used during development and testing
to catch potential bugs or invalid assumptions.
57. What is the difference between a local variable and an instance variable?
A local variable in Java is declared inside a method or a block and has a limited scope
within that method or block. An instance variable, also known as a member variable, is
declared within a class but outside any method and is accessible to all methods of the
class.
The "transient" keyword in Java is used to indicate that a variable should not be
serialized during object serialization. When an object is deserialized, transient variables
are set to their default values.
The "static" block in Java is used to initialize static variables or perform one-time
initialization tasks for a class. It is executed when the class is loaded into memory, before
any objects of that class are created.
The "strictfp" keyword in Java is used to ensure strict adherence to the IEEE 754 standard
for floating-point calculations. It ensures consistent results across different platforms by
disabling some optimizations that can affect precision.
61. What is the difference between a public class and a default (package-private) class?
A public class in Java can be accessed from any other class, regardless of the package
they belong to. A default class, also known as a package-private class, is only accessible
within the same package and cannot be accessed from outside the package.
The "enum" keyword in Java is used to define an enumeration, which is a special type
that represents a fixed set of constants. It allows for more structured and type-safe
representation of predefined values.
63. What is the purpose of the "break" and "continue" statements in Java?
The "break" statement in Java is used to terminate the execution of a loop or switch
statement and resume execution after the loop or switch block. The "continue" statement
is used to skip the current iteration of a loop and move to the next iteration.
66. What is the difference between the pre-increment and post-increment operators?
The pre-increment operator (++i) in Java increments the value of a variable and returns
the incremented value, while the post-increment operator (i++) increments the value of
a variable but returns the original value before the increment.
67. What is the difference between the pre-decrement and post-decrement operators?
The pre-decrement operator (--i) in Java decrements the value of a variable and
returns the decremented value, while the post-decrement operator (i--) decrements the
value of a variable but returns the original value before the decrement.
The "StringBuffer" class in Java is used to create and manipulate mutable sequences of
characters, similar to the "StringBuilder" class. However, "StringBuffer" is synchronized and
thread-safe, making it suitable for multi-threaded environments.
The "Math.random()" method in Java returns a random double value between 0.0
(inclusive) and 1.0 (exclusive). It is often used to generate random numbers or simulate
random behavior.
The "Character" class in Java provides methods for working with individual characters,
such as checking for character types (letters, digits, whitespace), converting case, and
performing character-based operations.
The "Integer" class in Java is a wrapper class that provides methods for working with
integer values, such as converting strings to integers, performing arithmetic operations,
and converting integers to different representations (binary, hexadecimal).
The "Double" class in Java is a wrapper class that provides methods for working with
double-precision floating-point values. It offers functionality for parsing strings,
performing arithmetic operations, and converting doubles to different representations
(binary, hexadecimal).
The "System" class in Java provides access to system resources and allows interaction
with the system environment. It contains methods for standard input/output, error
output, current time, copying arrays, and more.
75. What is the purpose of the "File" class in Java?
The "File" class in Java is used to represent and manipulate file and directory paths. It
provides methods for creating, deleting, renaming, and querying file properties such as
size, last modified date, and permissions.
The "StringBuilder" class in Java is used to create and manipulate mutable sequences of
characters. It provides methods for appending, inserting, deleting, and modifying
character sequences efficiently.
The "HashSet" class in Java is an implementation of the Set interface that stores unique
elements in no particular order. It provides constant-time performance for basic
operations like adding, removing, and checking for the presence of elements.
The "HashMap" class in Java is an implementation of the Map interface that stores key-
value pairs. It provides fast retrieval and insertion of elements based on their keys and
allows for efficient mapping and lookup operations.
The "LinkedList" class in Java is an implementation of the List interface that uses a
doubly-linked list to store elements. It provides efficient insertion and removal of
elements at both ends of the list but slower random access.
The "Comparable" interface in Java is used to define the natural ordering of objects of a
class. It provides a method, "compareTo()", that allows objects to be compared and
sorted based on their natural order.
The "super" keyword in Java is used to refer to the superclass of a class or to call the
superclass's constructor, methods, or variables. It is primarily used to differentiate
between superclass and subclass members with the same name.
The "final" keyword in Java is used to define constants, make variables unchangeable, or
prevent method overriding or class inheritance. It ensures that the value of a variable or
the implementation of a method or class cannot be modified.
The "static" keyword in Java is used to define class-level variables and methods that are
shared among all instances of a class. It allows accessing variables or methods without
creating an instance of the class.
The "interface" keyword in Java is used to define interfaces, which declare methods that
implementing classes must provide. It allows for multiple inheritance by implementing
multiple interfaces and enables the concept of polymorphism.
The "package" keyword in Java is used to define a package, which is a way to organize
related classes and interfaces. It provides a hierarchical structure and helps prevent
naming conflicts between classes.
The "import" keyword in Java is used to import classes, interfaces, or packages into a
source file. It allows using classes from other packages without specifying their fully
qualified names.
95. What is the purpose of the "throw" keyword in Java?
The "throw" keyword in Java is used to manually throw an exception. It is typically used
when a program encounters an error or exceptional situation that cannot be handled,
and the control should be transferred to an exception handler.
The "throws" keyword in Java is used in method declarations to specify that a method
may throw certain types of exceptions. It allows the caller of the method to handle the
exception or propagate it further.
The "try-catch-finally" block in Java is used to handle exceptions. The "try" block contains
the code that may throw an exception, the "catch" block catches and handles the
exception, and the "finally" block contains cleanup code that is executed regardless of
whether an exception occurs or not.
The "instanceof" operator in Java is used to check the type of an object at runtime. It
returns a boolean value indicating whether an object is an instance of a particular class
or implements a specific interface.
The "break" statement in Java is used to terminate the execution of a loop or switch
statement. It allows exiting a loop prematurely or skipping the remaining cases in a
switch statement.
The "continue" statement in Java is used to skip the current iteration of a loop and
continue with the next iteration. It allows skipping certain iterations based on specific
conditions without exiting the loop entirely.