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
floatanddoublein Java?floatis a 32-bit floating-point type, whiledoubleis 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
Stringclass in Java?- The
Stringclass 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
finalkeyword in Java used for?- The
finalkeyword 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
ifstatement in Java?- An
ifstatement 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
forloop in Java?- A
forloop is used for iterating over a range of values. It has three parts: initialization, condition, and increment/decrement.
- A
- What is a
whileloop in Java used for?- A
whileloop repeatedly executes a block of code as long as a condition istrue.
- A
- What is the
breakstatement in Java used for?- The
breakstatement is used to exit a loop prematurely, terminating the loop’s execution.
- The
- Explain the
continuestatement in Java.- The
continuestatement is used to skip the current iteration of a loop and continue with the next one.
- The
- What is the
switchstatement in Java?- The
switchstatement is used to select one of many code blocks to be executed. It’s often used as an alternative to longif-elsechains.
- The
- What is the
do-whileloop in Java used for?- The
do-whileloop is similar to awhileloop 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-elsestatement in a single line.
- A ternary conditional expression is a compact way to write an
int result = (condition) ? valueIfTrue : valueIfFalse;
- What is a labeled
breakorcontinuein Java?- A labeled
breakorcontinueallows 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
returnstatement in Java?- The
returnstatement 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
statickeyword in Java used for?- The
statickeyword 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
thiskeyword in Java used for?- The
thiskeyword refers to the current instance of the class and is often used to distinguish instance variables from method parameters.
- The
- What is the
superkeyword in Java?- The
superkeyword 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
newkeyword 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
thisreference in a constructor?- The
thisreference 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
staticblock in Java?- The
staticblock is used to initialize static variables or execute static code when a class is loaded into memory.
- The
- What is the
instanceofoperator in Java used for?- The
instanceofoperator checks if an object is an instance of a specific class or interface and returnstrueorfalseaccordingly.
- 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
finalclass in Java?- A
finalclass 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
superkeyword in Java used for?- The
superkeyword 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...catchblocks. Code within thetryblock is monitored for exceptions, and if one is caught, it is handled in thecatchblock.
- Exceptions are handled using
- What is the purpose of the
finallyblock in Java?- The
finallyblock is used to define code that will be executed regardless of whether an exception is raised or not.
- The
- What is the
throwstatement in Java used for?- The
throwstatement 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
assertstatement in Java?assertis used for debugging to check if an expression istrue, and if not, it raises anAssertionError.
- What is the
try...with...resourcesstatement in Java?- The
try...with...resourcesstatement is used for automatic resource management, ensuring that resources like files are closed after being used.
- The
- What is the
throwskeyword in Java?- The
throwskeyword 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
catchstatement without an exception type in Java?- A
catchstatement without a specified exception type catches any exception that is not explicitly handled by othercatchblocks.
- 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, andMapin Java?Listis an ordered collection that allows duplicates,Setis an unordered collection that does not allow duplicates, andMapis a collection of key-value pairs.
- Explain the
ArrayListclass in Java.ArrayListis a dynamic array that can grow or shrink in size. It is part of the Java Collections Framework.
- What is the difference between
ArrayListandLinkedListin Java?ArrayListis backed by an array, allowing fast random access but slower insertions and deletions.LinkedListis backed by a doubly-linked list, allowing fast insertions and deletions but slower access.
- What is the
HashSetclass in Java?HashSetis an implementation of theSetinterface. It uses a hash table to store elements and does not allow duplicates.
- Explain the
HashMapclass in Java.HashMapis an implementation of theMapinterface. It stores key-value pairs and allows fast retrieval of values based on their keys.
- What is the
Iteratorinterface in Java used for?- The
Iteratorinterface 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
ListIteratorinterface in Java?- The
ListIteratorinterface 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
Collectionsclass in Java used for?- The
Collectionsclass provides static methods for working with collections, such as sorting, shuffling, and searching.
- The
- What is the
Comparatorinterface in Java used for?- The
Comparatorinterface 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
Threadclass or implementing theRunnableinterface and then overriding therun()method.
- You can create a thread by extending the
- What is the
synchronizedkeyword in Java used for?- The
synchronizedkeyword 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, andnotifyAllmethods in Java?- These methods are used for inter-thread communication.
waitmakes a thread wait,notifywakes up one waiting thread, andnotifyAllwakes 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
joinmethod in Java used for?- The
joinmethod is used to wait for a thread to finish its execution before moving on to the next step.
- The
- Explain the
volatilekeyword in Java.- The
volatilekeyword 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, andFileOutputStreamfor 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
FileInputStreamandBufferedReaderto read from a file.
- You can use classes like
- How do you write to a file in Java?
- You can use classes like
FileOutputStreamandBufferedWriterto write to a file.
- You can use classes like
- What is the purpose of the
try-with-resourcesstatement in Java file handling?- The
try-with-resourcesstatement 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
Serializableinterface in Java used for?- The
Serializableinterface is used to mark a class as serializable, allowing its objects to be converted to byte streams.
- The
- Explain the purpose of the
transientkeyword in Java serialization.- The
transientkeyword 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
Cloneableinterface 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.