100 Java interview questions along with their short answers:
Basic Java Questions:
- What is Java?
- Java is a high-level, object-oriented, and platform-independent programming language.
- Who created Java, and when?
- Java was created by James Gosling and Mike Sheridan at Sun Microsystems in 1991.
- Explain the “Write Once, Run Anywhere” concept in Java.
- Java programs can run on any platform with a Java Virtual Machine (JVM) without modification.
- What is the latest version of Java?
- As of my last knowledge update in September 2021, the latest stable version was Java 17.
- What is the Java Virtual Machine (JVM)?
- The JVM is an integral part of Java that executes compiled Java code (bytecode) and provides platform independence.
- Explain the difference between JDK, JRE, and JVM.
- JDK (Java Development Kit) includes tools for Java development.
- JRE (Java Runtime Environment) includes the JVM and libraries for running Java applications.
- JVM (Java Virtual Machine) executes Java bytecode.
- What are the main principles of object-oriented programming (OOP)?
- OOP principles include encapsulation, inheritance, polymorphism, and abstraction.
- What is the difference between a class and an object in Java?
- A class is a blueprint for objects, while an object is an instance of a class.
- Explain the concept of inheritance in Java.
- Inheritance allows a class to inherit attributes and methods from another class. It promotes code reuse.
- What is a constructor in Java?
- A constructor is a special method used to initialize objects. It has the same name as the class and no return type.
Data Types and Variables:
- What are the eight primitive data types in Java?
- The eight primitive data types are byte, short, int, long, float, double, char, and boolean.
- How do you declare a variable in Java?
- Variables are declared by specifying the data type followed by the variable name, e.g.,
int age;
.
- Variables are declared by specifying the data type followed by the variable name, e.g.,
- What is the difference between
float
anddouble
in Java?float
is a 32-bit floating-point type, whiledouble
is a 64-bit floating-point type, providing greater precision.
- What is a Java wrapper class?
- Wrapper classes provide objects for primitive data types. They allow you to perform operations and use data structures that require objects.
- Explain the concept of autoboxing and unboxing in Java.
- Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class, and unboxing is the reverse.
- What is the
String
class in Java?- The
String
class is used to create and manipulate strings in Java. Strings are immutable in Java.
- The
- How do you compare two strings in Java?
- You should use the
.equals()
method to compare the contents of two strings, not the==
operator, which checks for reference equality.
- You should use the
- What is the difference between
==
and.equals()
in Java?==
checks for reference equality, while.equals()
checks for value equality when comparing objects.
- What is the
final
keyword in Java used for?- The
final
keyword can be applied to variables, methods, and classes. It makes variables constants, prevents method overriding, and classes from being extended.
- The
- What is the scope of a variable in Java?
- The scope of a variable determines where it can be accessed. Local variables have limited scope, while instance variables have class-wide scope.
Control Structures:
- What is an
if
statement in Java?- An
if
statement is used for conditional execution of code. It allows you to execute code blocks based on whether a condition istrue
.
- An
- How do you write a
for
loop in Java?- A
for
loop is used for iterating over a range of values. It has three parts: initialization, condition, and increment/decrement.
- A
- What is a
while
loop in Java used for?- A
while
loop repeatedly executes a block of code as long as a condition istrue
.
- A
- What is the
break
statement in Java used for?- The
break
statement is used to exit a loop prematurely, terminating the loop’s execution.
- The
- Explain the
continue
statement in Java.- The
continue
statement is used to skip the current iteration of a loop and continue with the next one.
- The
- What is the
switch
statement in Java?- The
switch
statement is used to select one of many code blocks to be executed. It’s often used as an alternative to longif-else
chains.
- The
- What is the
do-while
loop in Java used for?- The
do-while
loop is similar to awhile
loop but guarantees that the code block is executed at least once before checking the condition.
- The
- What is a ternary conditional expression in Java?
- A ternary conditional expression is a compact way to write an
if-else
statement in a single line.
- A ternary conditional expression is a compact way to write an
int result = (condition) ? valueIfTrue : valueIfFalse;
- What is a labeled
break
orcontinue
in Java?- A labeled
break
orcontinue
allows you to specify which loop or switch statement to exit or continue when nested loops or switch statements are present.
- A labeled
- What is the purpose of the
return
statement in Java?- The
return
statement is used to exit a method and optionally return a value to the caller.
- The
Methods and Functions:
- What is a method in Java?
- A method is a block of code that performs a specific task when called. It is defined within a class.
- How do you define a method in Java?
- Methods are defined within a class using the
methodType methodName(parameters)
syntax.
- Methods are defined within a class using the
- What is method overloading in Java?
- Method overloading allows you to define multiple methods with the same name in the same class, but with different parameters.
- What is method overriding in Java?
- Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It promotes polymorphism.
- What is the
static
keyword in Java used for?- The
static
keyword makes a method or variable belong to the class, rather than an instance of the class. It allows you to call methods or access variables without creating an instance of the class.
- The
- What is the
this
keyword in Java used for?- The
this
keyword refers to the current instance of the class and is often used to distinguish instance variables from method parameters.
- The
- What is the
super
keyword in Java?- The
super
keyword is used to refer to the superclass or parent class. It’s often used to call a superclass’s constructor or access its methods and variables.
- The
- What are varargs in Java?
- Varargs (variable-length arguments) allow a method to accept a variable number of arguments. They are represented by an ellipsis
...
and must be the last parameter.
- Varargs (variable-length arguments) allow a method to accept a variable number of arguments. They are represented by an ellipsis
- What is method chaining in Java?
- Method chaining is a technique where methods return an object to allow cascading multiple method calls in a single line.
- What is a Java package?
- A package is a way to organize related classes and interfaces. It helps prevent naming conflicts and provides modularity.
Classes and Objects:
- What is a class in Java?
- A class is a blueprint or template for creating objects. It defines attributes (fields) and behaviors (methods).
- How do you create an object from a class in Java?
- Objects are created by using the
new
keyword followed by the class constructor.
- Objects are created by using the
ClassName obj = new ClassName();
- What is an instance variable in Java?
- An instance variable is a variable declared in a class but outside of any method. It is associated with each instance of the class.
- What is a constructor in Java?
- A constructor is a special method that initializes an object. It has the same name as the class and no return type.
- What is the
this
reference in a constructor?- The
this
reference in a constructor is used to refer to the current object being initialized. It is often used to distinguish between instance variables and parameters.
- The
- What is the purpose of the
static
block in Java?- The
static
block is used to initialize static variables or execute static code when a class is loaded into memory.
- The
- What is the
instanceof
operator in Java used for?- The
instanceof
operator checks if an object is an instance of a specific class or interface and returnstrue
orfalse
accordingly.
- The
- What is encapsulation in Java?
- Encapsulation is one of the four fundamental OOP concepts. It is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit (class).
- What is the purpose of the
final
class in Java?- A
final
class cannot be extended or subclassed. It’s often used to prevent inheritance or to create immutable classes.
- A
- Explain the concept of abstraction in Java.
- Abstraction is one of the four fundamental OOP concepts. It involves simplifying complex reality by modeling classes based on their essential characteristics.
Inheritance and Polymorphism:
- What is inheritance in Java?
- Inheritance is the mechanism by which one class acquires the properties and behaviors of another class. It promotes code reusability.
- What is a superclass and a subclass in Java?
- A superclass (parent class) is a class that is inherited from, and a subclass (child class) is a class that inherits from a superclass.
- What is method overriding in Java?
- Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
- What is the
super
keyword in Java used for?- The
super
keyword is used to refer to the superclass or parent class. It’s often used to call a superclass’s constructor or access its methods and variables.
- The
- Explain the concept of polymorphism in Java.
- Polymorphism allows objects of different classes to be treated as objects of a common superclass. It’s often achieved through method overriding and interfaces.
- What is an interface in Java?
- An interface is a reference type that defines a list of abstract methods. It allows classes to implement those methods and achieve multiple inheritance.
- What is the difference between an abstract class and an interface in Java?
- An abstract class can have a combination of abstract and concrete methods, while an interface only contains abstract methods. A class can inherit from only one abstract class but implement multiple interfaces.
- What is method overloading in Java?
- Method overloading is the practice of defining two or more methods in the same class with the same name but different parameters.
- What is a static method in Java?
- A static method belongs to the class rather than an instance of the class. It can be called using the class name and is often used for utility functions.
- What is a final method in Java?
- A final method cannot be overridden in a subclass. It is often used to ensure that the behavior of a method is not changed in any subclass.
Exception Handling:
- What is an exception in Java?
- An exception is an event that occurs during the execution of a program, disrupting the normal flow of instructions.
- How do you handle exceptions in Java?
- Exceptions are handled using
try...catch
blocks. Code within thetry
block is monitored for exceptions, and if one is caught, it is handled in thecatch
block.
- Exceptions are handled using
- What is the purpose of the
finally
block in Java?- The
finally
block is used to define code that will be executed regardless of whether an exception is raised or not.
- The
- What is the
throw
statement in Java used for?- The
throw
statement is used
- The
- What are checked and unchecked exceptions in Java?
- Checked exceptions are those that are checked at compile time, and you are required to catch or declare them. Unchecked exceptions are checked at runtime and don’t require explicit handling.
- What is exception chaining in Java?
- Exception chaining allows you to raise a new exception while preserving the original exception’s context.
- What is the purpose of the
assert
statement in Java?assert
is used for debugging to check if an expression istrue
, and if not, it raises anAssertionError
.
- What is the
try...with...resources
statement in Java?- The
try...with...resources
statement is used for automatic resource management, ensuring that resources like files are closed after being used.
- The
- What is the
throws
keyword in Java?- The
throws
keyword is used in method signatures to indicate that a method may throw specific exceptions, which should be handled by the caller.
- The
- What is the
catch
statement without an exception type in Java?- A
catch
statement without a specified exception type catches any exception that is not explicitly handled by othercatch
blocks.
- A
Java Collections:
- What is a collection in Java?
- A collection is a framework that provides an architecture to store and manipulate a group of objects.
- What is the difference between
List
,Set
, andMap
in Java?List
is an ordered collection that allows duplicates,Set
is an unordered collection that does not allow duplicates, andMap
is a collection of key-value pairs.
- Explain the
ArrayList
class in Java.ArrayList
is a dynamic array that can grow or shrink in size. It is part of the Java Collections Framework.
- What is the difference between
ArrayList
andLinkedList
in Java?ArrayList
is backed by an array, allowing fast random access but slower insertions and deletions.LinkedList
is backed by a doubly-linked list, allowing fast insertions and deletions but slower access.
- What is the
HashSet
class in Java?HashSet
is an implementation of theSet
interface. It uses a hash table to store elements and does not allow duplicates.
- Explain the
HashMap
class in Java.HashMap
is an implementation of theMap
interface. It stores key-value pairs and allows fast retrieval of values based on their keys.
- What is the
Iterator
interface in Java used for?- The
Iterator
interface is used to iterate through the elements of a collection, allowing you to remove elements during the iteration.
- The
- What is the purpose of the
ListIterator
interface in Java?- The
ListIterator
interface is a bidirectional iterator for lists. It allows you to traverse a list in both directions and modify elements during iteration.
- The
- What is the
Collections
class in Java used for?- The
Collections
class provides static methods for working with collections, such as sorting, shuffling, and searching.
- The
- What is the
Comparator
interface in Java used for?- The
Comparator
interface allows you to define custom comparison logic for objects, making it useful for sorting and ordering collections.
- The
Multithreading:
- What is multithreading in Java?
- Multithreading is the concurrent execution of two or more threads to achieve maximum CPU utilization.
- How do you create a thread in Java?
- You can create a thread by extending the
Thread
class or implementing theRunnable
interface and then overriding therun()
method.
- You can create a thread by extending the
- What is the
synchronized
keyword in Java used for?- The
synchronized
keyword is used to create synchronized blocks and methods to ensure that only one thread can access the synchronized code at a time.
- The
- What is the purpose of the
wait
,notify
, andnotifyAll
methods in Java?- These methods are used for inter-thread communication.
wait
makes a thread wait,notify
wakes up one waiting thread, andnotifyAll
wakes up all waiting threads.
- These methods are used for inter-thread communication.
- What is the Java Memory Model (JMM)?
- JMM defines how Java threads interact with memory, ensuring that changes made by one thread are visible to other threads.
- What is thread priority in Java?
- Thread priority is a way to indicate the importance of a thread’s execution. It is used by the JVM’s thread scheduler.
- What is the
join
method in Java used for?- The
join
method is used to wait for a thread to finish its execution before moving on to the next step.
- The
- Explain the
volatile
keyword in Java.- The
volatile
keyword is used to declare a variable as “volatile,” ensuring that reads and writes to the variable are visible to other threads.
- The
- What is a daemon thread in Java?
- A daemon thread is a background thread that runs without blocking the program from exiting. It is often used for tasks like garbage collection.
- What is deadlock in multithreading, and how can it be avoided?
- Deadlock occurs when two or more threads are unable to proceed because each is waiting for the other to release a resource. To avoid deadlock, use proper synchronization and a well-defined order for resource acquisition.
File Handling:
- What is file handling in Java?
- File handling involves reading from and writing to files. Java provides classes like
File
,FileInputStream
, andFileOutputStream
for this purpose.
- File handling involves reading from and writing to files. Java provides classes like
- How do you read from a file in Java?
- You can use classes like
FileInputStream
andBufferedReader
to read from a file.
- You can use classes like
- How do you write to a file in Java?
- You can use classes like
FileOutputStream
andBufferedWriter
to write to a file.
- You can use classes like
- What is the purpose of the
try-with-resources
statement in Java file handling?- The
try-with-resources
statement ensures that resources (such as file streams) are closed properly when the block is exited.
- The
- What is serialization in Java?
- Serialization is the process of converting an object into a byte stream, making it easy to store, transmit, or recreate the object.
- What is deserialization in Java?
- Deserialization is the process of converting a byte stream back into an object, effectively recreating the original object.
- What is the
Serializable
interface in Java used for?- The
Serializable
interface is used to mark a class as serializable, allowing its objects to be converted to byte streams.
- The
- Explain the purpose of the
transient
keyword in Java serialization.- The
transient
keyword is used to exclude specific fields from being serialized.
- The
- What is object cloning in Java?
- Object cloning is the process of creating a duplicate of an
Cloneable
interface and theclone()
method for this purpose. - What is the difference between character stream and byte stream in file handling?
- Character streams are used for reading and writing character data (text), while byte streams are used for reading and writing binary data.