0% found this document useful (0 votes)
1 views21 pages

Java Top 100 Interview Questions Answers

The document provides a comprehensive list of the top 100 Java interview questions and answers, covering essential topics such as Core Java, OOP principles, data types, collections, and more. Each question is followed by a concise explanation, making it a valuable resource for preparing for Java interviews. Key concepts include JDK, JRE, JVM, object-oriented programming principles, and various data structures in Java.

Uploaded by

joelmanohar77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views21 pages

Java Top 100 Interview Questions Answers

The document provides a comprehensive list of the top 100 Java interview questions and answers, covering essential topics such as Core Java, OOP principles, data types, collections, and more. Each question is followed by a concise explanation, making it a valuable resource for preparing for Java interviews. Key concepts include JDK, JRE, JVM, object-oriented programming principles, and various data structures in Java.

Uploaded by

joelmanohar77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Top 100 Java Interview Questions and Answers

Core Java - JDK, JRE, JVM


1. What is JDK, JRE, and JVM?
JDK stands for Java Development Kit.
It is used to develop, compile, and run Java programs.

JRE stands for Java Runtime Environment.


It is used only to run Java applications.
JVM stands for Java Virtual Machine.
It executes Java bytecode.
JDK contains JRE, and JRE contains JVM.
For development we need JDK, but for only running Java applications JRE is enough.

2. Why is Java platform-independent?


Java is platform-independent because Java code is compiled into bytecode.
Bytecode is not specific to any operating system.
This bytecode can run on any machine that has a JVM.
The JVM converts bytecode into machine-specific instructions.
That is why Java follows "write once, run anywhere".

The source code does not need to be recompiled for every platform.

3. What is bytecode?
Bytecode is the intermediate code generated by the Java compiler.

It is created after compiling a .java file.


The bytecode is stored in a .class file.
Bytecode is not machine code.
It is executed by the JVM.
Because of bytecode, Java becomes platform-independent.

4. What is JVM architecture?


JVM architecture explains how JVM loads and executes Java bytecode.
It mainly contains Class Loader, Runtime Data Area, Execution Engine, and Native Method Interface.
Class Loader loads .class files into memory.
Runtime Data Area contains memory areas like heap, stack, method area, and PC register.
Execution Engine executes bytecode.
Garbage Collector removes unused objects from heap memory.

5. What is the role of the compiler?


The Java compiler converts source code into bytecode.
The source code is written in a .java file.

Top 100 Java Interview Questions and Answers Page 1


After compilation, a .class file is created.
The compiler checks syntax errors.
It also checks type-related errors.
The generated bytecode is later executed by the JVM.
javac [Link]
java Main

Data Types and Variables


6. What are primitive data types?
Primitive data types are basic data types provided by Java.

They store simple values directly.


Java has eight primitive data types.
They are byte, short, int, long, float, double, char, and boolean.
Primitive types are faster and use less memory.
They are not objects.

7. Difference between primitive and non-primitive data types?


Primitive data types store actual values.
Non-primitive data types store references to objects.
Primitive types are predefined by Java.
Non-primitive types can be built-in or user-defined.
Examples of primitive types are int, char, and boolean.

Examples of non-primitive types are String, arrays, classes, and interfaces.


Primitive types cannot call methods, but non-primitive types can.

8. What is type casting?


Type casting means converting one data type into another data type.
It is used when we want to assign a value of one type to another type.
In Java, casting can be implicit or explicit.
Implicit casting happens automatically.
Explicit casting is done manually by the programmer.
Type casting is common with numeric data types.
int a = 10;
double b = a;

9. Difference between implicit and explicit casting?


Implicit casting is done automatically by Java.
It happens when a smaller type is converted into a larger type.
Explicit casting is done manually by the programmer.
It happens when a larger type is converted into a smaller type.

Implicit casting is safe.


Explicit casting may cause data loss.

Top 100 Java Interview Questions and Answers Page 2


int a = 10;
double b = a; // implicit
int c = (int) b; // explicit

10. Types of variables in Java?


Java has three main types of variables.

Local variables are declared inside a method or block.


Instance variables are declared inside a class but outside methods.
Static variables are declared using the static keyword.
Local variables are created when a method runs.
Instance variables belong to an object.
Static variables belong to the class.

OOPs
11. What is OOP?
OOP stands for Object-Oriented Programming.
It is a programming approach based on objects.
Objects contain data and behavior.
Data is represented by variables.
Behavior is represented by methods.
OOP makes code reusable, secure, and easy to maintain.
Java is mainly an object-oriented programming language.

12. What are the four pillars of OOP?


The four pillars of OOP are abstraction, encapsulation, inheritance, and polymorphism.
Abstraction hides implementation details.

Encapsulation wraps data and methods together.


Inheritance allows one class to reuse another class.
Polymorphism allows one method or object to behave in many forms.
These concepts make Java code flexible and reusable.

13. What is Abstraction?


Abstraction means hiding internal implementation and showing only important details.
It helps reduce complexity.
In Java, abstraction is achieved using abstract classes and interfaces.
For example, when we drive a car, we use steering and brakes without knowing internal engine details.
Abstraction focuses on what an object does.
It does not focus on how it does it.

14. What is Encapsulation?


Encapsulation means wrapping data and methods inside a class.
It is used to protect data from direct access.
Variables are usually declared as private.

Top 100 Java Interview Questions and Answers Page 3


Public getters and setters are used to access and update the data.
Encapsulation improves security.
It also makes code easier to maintain.

15. What is Inheritance?


Inheritance means one class can acquire properties and methods of another class.
The parent class is called superclass.
The child class is called subclass.
Java uses the extends keyword for inheritance.
It helps with code reuse.
It also supports method overriding.
class Dog extends Animal {
}

16. What is Polymorphism?


Polymorphism means one thing having many forms.

In Java, polymorphism is achieved using method overloading and method overriding.


Method overloading is compile-time polymorphism.
Method overriding is runtime polymorphism.
It makes code flexible.
It allows the same method name to behave differently.

17. Difference between abstraction and encapsulation?


Abstraction hides implementation details.
Encapsulation hides data.
Abstraction focuses on what an object does.
Encapsulation focuses on protecting how data is accessed.
Abstraction is achieved using abstract classes and interfaces.
Encapsulation is achieved using private variables and public getters/setters.

Both improve code quality and maintainability.

18. Difference between abstract class and interface?


An abstract class can have abstract and non-abstract methods.

An interface mainly defines a contract that classes must follow.


A class can extend only one abstract class.
A class can implement multiple interfaces.
Abstract classes can have constructors.
Interfaces cannot have normal constructors.
Use abstract class when classes are closely related.
Use interface when unrelated classes need common behavior.

19. Why doesn't Java support multiple inheritance?


Java does not support multiple inheritance with classes to avoid ambiguity.

If two parent classes have the same method, the child class may get confused about which method to use.

Top 100 Java Interview Questions and Answers Page 4


This problem is called the Diamond Problem.
To keep Java simple and safe, multiple inheritance with classes is not allowed.
Java supports multiple inheritance using interfaces.
Interfaces avoid this problem because implementation is handled by the class.

20. What is the Diamond Problem?


The Diamond Problem occurs in multiple inheritance.
It happens when a child class inherits from two parent classes that have the same method.
The compiler may not know which parent method should be used.
This creates ambiguity.
Java avoids this problem by not allowing multiple inheritance with classes.

Java allows multiple inheritance through interfaces with clear rules.

Classes and Objects


21. What is a class?
A class is a blueprint or template for creating objects.
It defines variables and methods.
Variables represent data.

Methods represent behavior.


A class does not occupy memory for object data until an object is created.
Example: Student can be a class.

22. What is an object?


An object is an instance of a class.
It has state and behavior.
State is stored in variables.
Behavior is defined by methods.
Objects are created using the new keyword.
Example: Student s = new Student();.

23. Difference between class and object?


A class is a blueprint.
An object is a real instance of that blueprint.
A class defines properties and behavior.
An object uses those properties and behavior.

A class is logical.
An object is physical because it occupies memory.

24. What is the this keyword?


this refers to the current object.
It is used to access current class variables and methods.
It is commonly used when local variable and instance variable names are the same.

Top 100 Java Interview Questions and Answers Page 5


It can also be used to call another constructor in the same class.
this improves clarity in code.
class Student {
String name;

Student(String name) {
[Link] = name;
}
}

25. What is the difference between object and reference?


An object is the actual instance stored in heap memory.
A reference is a variable that stores the address of an object.
The reference is used to access the object.
Multiple references can point to the same object.

If no reference points to an object, it becomes eligible for garbage collection.


Student s = new Student();

Here, s is the reference and new Student() is the object.

Constructors
26. What is a constructor?
A constructor is a special method used to initialize an object.
Its name must be the same as the class name.
It has no return type.
It is called automatically when an object is created.
Constructors can set initial values for variables.
Java provides a default constructor if no constructor is written.

27. Types of constructors?


Java mainly has two types of constructors.
A default constructor has no parameters.

A parameterized constructor has parameters.


The default constructor initializes values with defaults.
The parameterized constructor initializes values with user-provided data.
Constructors can also be overloaded.

28. Difference between constructor and method?


A constructor initializes an object.
A method performs an operation or behavior.
Constructor name must be the same as class name.
Method name can be anything valid.
Constructor has no return type.

Method can have a return type.


Constructor is called automatically during object creation.

Top 100 Java Interview Questions and Answers Page 6


Method is called manually.

29. What is constructor overloading?


Constructor overloading means having multiple constructors in the same class.
Each constructor must have different parameters.
It allows objects to be initialized in different ways.
It is an example of compile-time polymorphism.
Constructor overloading improves flexibility.
class Student {
Student() {
}

Student(String name) {
}
}

30. What is this()?


this() is used to call another constructor of the same class.
It must be the first statement inside a constructor.

It is useful for constructor chaining.


It helps avoid duplicate initialization code.
It cannot be used inside normal methods.
class Student {
Student() {
this("Unknown");
}

Student(String name) {
[Link](name);
}
}

31. What is super()?


super() is used to call the parent class constructor.
It must be the first statement inside a child class constructor.
If we do not write it, Java automatically adds super().

It is useful when the parent class must be initialized first.


super can also be used to access parent class methods and variables.

32. Can constructors be overridden?


No, constructors cannot be overridden.
Overriding requires inheritance and the same method signature.
Constructors are not inherited by child classes.
Because constructors are not inherited, they cannot be overridden.
But constructors can be overloaded in the same class.

String
33. What is String?
String is a class in Java used to store a sequence of characters.

Top 100 Java Interview Questions and Answers Page 7


It belongs to the [Link] package.
String is not a primitive data type.
String objects are immutable.
Once a String object is created, its value cannot be changed.
Strings are commonly used for text handling.

34. Why is String immutable?


String is immutable for security, performance, and thread safety.
String values are used in important areas like class loading, file paths, and database connections.
Immutability prevents accidental changes.
It also allows String Pool optimization.

Because Strings cannot change, they are safe to share between threads.
This makes String reliable and efficient.

35. What is String Pool?


String Pool is a special memory area inside heap memory.
It stores String literals.
When we create a String literal, Java first checks the String Pool.
If the same value already exists, Java reuses it.
If not, Java creates a new String in the pool.
String Pool saves memory.
String a = "Java";
String b = "Java";

Here, both references can point to the same pooled object.

36. Difference between String, StringBuilder, and StringBuffer?


String is immutable.

StringBuilder and StringBuffer are mutable.


StringBuilder is faster but not thread-safe.
StringBuffer is thread-safe but slower.
Use String when data does not change frequently.
Use StringBuilder in single-threaded code with frequent changes.
Use StringBuffer in multithreaded code with frequent changes.

37. Difference between == and equals()?


== compares references for objects.
It checks whether two references point to the same object.
equals() compares object values when properly implemented.
For String, equals() compares text content.
Use equals() to compare String values.

Use == mostly for primitive comparison or reference checking.

38. How many ways can you create a String?


String can be created mainly in two ways.

Top 100 Java Interview Questions and Answers Page 8


The first way is using a String literal.
The second way is using the new keyword.
String literals are stored in the String Pool.
Strings created with new are stored as new objects in heap memory.
String a = "Java";
String b = new String("Java");

Collections
39. What is Collection Framework?
The Collection Framework is a set of interfaces and classes used to store groups of objects.

It provides data structures like List, Set, Queue, and Map.


It helps perform operations like add, remove, search, and sort.
It reduces programming effort.
It is part of the [Link] package.
Common classes include ArrayList, LinkedList, HashSet, TreeSet, and HashMap.

40. Difference between List, Set, and Map?


List stores ordered elements and allows duplicates.
Set stores unique elements and does not allow duplicates.
Map stores key-value pairs.
List elements are accessed by index.
Set does not guarantee index-based access.

Map uses keys to access values.


Examples are ArrayList, HashSet, and HashMap.

41. What is ArrayList?


ArrayList is a resizable array implementation of the List interface.
It allows duplicate elements.
It maintains insertion order.
It allows random access using index.
It is faster for reading data.
It is slower for frequent insertion and deletion in the middle.
ArrayList is not synchronized.

42. Difference between ArrayList and LinkedList?


ArrayList uses a dynamic array internally.
LinkedList uses nodes internally.
ArrayList is better for searching and reading.
LinkedList is better for frequent insertion and deletion.

ArrayList uses less memory.


LinkedList uses more memory because each node stores links.

Top 100 Java Interview Questions and Answers Page 9


Both allow duplicates and maintain insertion order.

43. What is HashSet?


HashSet is a class that implements the Set interface.
It stores unique elements only.
It does not maintain insertion order.
It uses hashing internally.
It allows one null value.
It is faster for search, add, and remove operations.
HashSet is not synchronized.

44. Difference between HashSet and TreeSet?


HashSet stores unique elements without order.
TreeSet stores unique elements in sorted order.
HashSet is faster than TreeSet.

TreeSet is slower because it maintains sorting.


HashSet allows one null value.
TreeSet generally does not allow null with natural sorting.
Use HashSet for speed and TreeSet for sorted data.

45. What is HashMap?


HashMap stores data in key-value pairs.
Keys must be unique.
Values can be duplicate.
It allows one null key and multiple null values.
It does not maintain insertion order.
It uses hashing internally.
HashMap is not synchronized.

46. How does HashMap work internally?


HashMap uses an array of buckets internally.
When we put a key-value pair, Java calculates the hash code of the key.

The hash code helps find the bucket index.


The entry is stored in that bucket.
When we get a value, Java again calculates the bucket using the key.
If multiple keys go to the same bucket, collision handling is used.
From Java 8, long collision chains can become balanced trees.

47. What is a collision in HashMap?


A collision happens when two different keys produce the same bucket index.
In that case, multiple entries are stored in the same bucket.

Java handles collisions using linked lists or balanced trees.


The equals() method is used to identify the correct key.

Top 100 Java Interview Questions and Answers Page 10


Good hashCode() implementation reduces collisions.
Collision handling is important for HashMap performance.

48. Difference between HashMap and Hashtable?


HashMap is not synchronized.
Hashtable is synchronized.
HashMap is faster.
Hashtable is slower because of synchronization.
HashMap allows one null key and multiple null values.
Hashtable does not allow null keys or null values.
HashMap is preferred in modern Java.

49. Difference between Comparable and Comparator?


Comparable defines natural sorting order.
Comparator defines custom sorting order.

Comparable has the compareTo() method.


Comparator has the compare() method.
Comparable is implemented by the class being sorted.
Comparator can be written separately.
Use Comparator when multiple sorting logics are needed.

50. What is Iterator?


Iterator is used to traverse elements of a collection.
It is part of the [Link] package.
It has methods like hasNext(), next(), and remove().
It works with collections like ArrayList and HashSet.
Iterator provides a standard way to access elements one by one.
It is safer than manually using indexes for some collections.

Exception Handling
51. What is an exception?
An exception is an unwanted event that occurs during program execution.
It disturbs the normal flow of the program.
Examples include dividing by zero, accessing null, or file not found.
Exceptions can be handled using try-catch blocks.

Exception handling helps programs continue safely.


Exceptions are objects in Java.

52. Difference between Error and Exception?


Error represents serious problems that applications usually cannot handle.
Examples are OutOfMemoryError and StackOverflowError.
Exception represents conditions that programs can handle.

Top 100 Java Interview Questions and Answers Page 11


Examples are IOException and NullPointerException.
Errors are mostly caused by system-level issues.
Exceptions are mostly caused by program-level issues.

53. What is exception handling?


Exception handling is a mechanism to handle runtime errors.
It prevents abnormal termination of the program.
Java uses try, catch, finally, throw, and throws.
Risky code is written in the try block.
Exception handling code is written in the catch block.
It makes applications more robust.

54. What is try-catch-finally?


try contains code that may throw an exception.
catch handles the exception thrown from the try block.

finally contains code that always executes.


The finally block is commonly used for cleanup.
Examples include closing files, database connections, or streams.
Even if an exception occurs, finally usually runs.

55. Difference between checked and unchecked exceptions?


Checked exceptions are checked at compile time.
The programmer must handle or declare them.
Examples are IOException and SQLException.
Unchecked exceptions are checked at runtime.
They usually occur due to programming mistakes.
Examples are NullPointerException and ArithmeticException.
Checked exceptions extend Exception.

Unchecked exceptions extend RuntimeException.

56. What is throw?


throw is used to explicitly throw an exception.

It is used inside a method or block.


It throws a single exception object.
It is commonly used for custom validation.
throw new IllegalArgumentException("Invalid age");

57. What is throws?


throws is used in a method declaration.
It tells the caller that the method may throw an exception.
It can declare multiple exceptions.

It is mostly used with checked exceptions.


The caller must handle or further declare the exception.

Top 100 Java Interview Questions and Answers Page 12


void readFile() throws IOException {
}

58. What is NullPointerException?


NullPointerException occurs when we try to use a null reference.
For example, calling a method on a null object causes it.
It is an unchecked exception.
It is one of the most common Java exceptions.
It can be avoided using null checks.
Java 8 Optional can also help handle null values.

59. How do you create a custom exception?


A custom exception is created by extending Exception or RuntimeException.
Extend Exception for checked custom exceptions.

Extend RuntimeException for unchecked custom exceptions.


Custom exceptions are used for application-specific errors.
They make error handling more meaningful.
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}

Multithreading
60. What is a thread?
A thread is a lightweight unit of execution.
It is part of a process.
Multiple threads can run inside one process.
Threads share the same memory of the process.
Java supports threads using the Thread class and Runnable interface.

Threads are useful for parallel tasks.

61. What is multithreading?


Multithreading means running multiple threads at the same time.

It helps perform multiple tasks together.


It improves performance for independent tasks.
It is useful in servers, games, background jobs, and real-time systems.
Thread execution is managed by JVM and operating system.
Synchronization is needed when threads share data.

62. Difference between process and thread?


A process is an independent program in execution.
A thread is a smaller unit inside a process.

Processes have separate memory.

Top 100 Java Interview Questions and Answers Page 13


Threads share memory of the same process.
Process switching is heavier.
Thread switching is lighter.
Multiple threads can exist inside one process.

63. How do you create a thread?


A thread can be created by extending the Thread class.
It can also be created by implementing the Runnable interface.
The Runnable approach is preferred because Java supports single inheritance.
After creating a thread, call the start() method.
The start() method internally calls run().
class MyTask implements Runnable {
public void run() {
[Link]("Thread running");
}
}

64. Difference between start() and run()?


start() creates a new thread.
It internally calls the run() method.

run() contains the actual task of the thread.


If we call run() directly, no new thread is created.
The method runs like a normal method call.
Always use start() to begin a new thread.

65. What is synchronization?


Synchronization is used to control access to shared resources.
It allows only one thread at a time to access synchronized code.
It prevents data inconsistency.
It is useful when multiple threads update the same data.
Java provides the synchronized keyword.
Synchronization can reduce performance if overused.

66. What is thread safety?


Thread safety means code works correctly when accessed by multiple threads.
A thread-safe program avoids data corruption.

Synchronization, locks, immutable objects, and concurrent collections help achieve thread safety.
String is thread-safe because it is immutable.
ConcurrentHashMap is a thread-safe collection.
Thread safety is important in multithreaded applications.

67. What is race condition?


A race condition occurs when multiple threads access shared data at the same time.
The final result depends on thread execution order.

This can produce incorrect or unpredictable results.

Top 100 Java Interview Questions and Answers Page 14


Race conditions happen mostly during read-update-write operations.
Synchronization can prevent race conditions.
Atomic classes can also help.

68. What is deadlock?


Deadlock occurs when two or more threads wait for each other forever.
Each thread holds one resource and waits for another resource.
As a result, none of the threads can continue.
Deadlock usually happens because of poor lock management.
It can be avoided by acquiring locks in a fixed order.
Timeout-based locking can also help.

Java 8
69. What is Lambda Expression?
A lambda expression is a short way to write an anonymous function.
It was introduced in Java 8.
It is mainly used with functional interfaces.
It makes code shorter and cleaner.

It is commonly used with collections and Stream API.


[Link](name -> [Link](name));

70. What is Functional Interface?


A functional interface is an interface with only one abstract method.
It can have default and static methods.
It is used with lambda expressions.
The @FunctionalInterface annotation is optional but recommended.
Examples are Runnable, Predicate, Consumer, and Function.

71. What is Streams API?


Stream API is used to process collections in a functional style.
It was introduced in Java 8.
It does not store data.

It works on data from collections or arrays.


It supports operations like filter, map, reduce, and collect.
Streams make code shorter and readable.

72. Difference between Collection and Stream?


Collection stores data.
Stream processes data.
Collection can be used multiple times.
Stream can usually be consumed only once.

Collection is eager.

Top 100 Java Interview Questions and Answers Page 15


Stream operations are mostly lazy.
Collection focuses on storage.
Stream focuses on computation.

73. What is filter()?


filter() is a Stream method used to select elements based on a condition.
It takes a Predicate as input.
It returns a new stream with matching elements.
It does not modify the original collection.
[Link]().filter(n -> n > 10);

74. What is map()?


map() is a Stream method used to transform elements.
It applies a function to each element.
It returns a new stream with transformed values.
It is commonly used to convert one type of data into another.
[Link]().map(name -> [Link]());

75. What is reduce()?


reduce() is used to combine stream elements into a single result.
It is commonly used for sum, multiplication, maximum, or minimum.

It takes an identity value and an accumulator function.


It is a terminal operation.
int sum = [Link]().reduce(0, (a, b) -> a + b);

76. What is Method Reference?


Method reference is a shorter way to write a lambda expression.
It refers to an existing method by name.
It uses the :: operator.
It improves readability when a lambda only calls one method.
[Link]([Link]::println);

77. What is Predicate?


Predicate is a functional interface introduced in Java 8.
It represents a condition.
It takes one input and returns a boolean value.
It is commonly used with filter().
Predicate is available in [Link].
Predicate<Integer> p = n -> n > 10;

78. What is Consumer?


Consumer is a functional interface introduced in Java 8.

It takes one input and returns nothing.


It is used when we want to perform an action on data.
It is commonly used with forEach().

Top 100 Java Interview Questions and Answers Page 16


Consumer is available in [Link].
Consumer<String> c = name -> [Link](name);

Advanced Java
79. What are Generics?
Generics allow us to write type-safe and reusable code.
They let us specify the type of data a class or method can use.
They are commonly used in collections.
Generics reduce the need for type casting.
They help catch errors at compile time.
ArrayList<String> names = new ArrayList<>();

80. What is Type Erasure?


Type erasure is the process where generic type information is removed at compile time.
Java uses type erasure to support backward compatibility.

At runtime, generic type details are not available in the same way.
For example, ArrayList<String> and ArrayList<Integer> are both treated as ArrayList at runtime.
Type checking happens mainly at compile time.

81. What are Annotations?


Annotations provide metadata about code.
They start with the @ symbol.
They do not directly change program logic.
Common annotations are @Override, @Deprecated, and @SuppressWarnings.
Frameworks like Spring use annotations heavily.
Custom annotations can also be created.

82. What is Reflection API?


Reflection API allows Java programs to inspect classes at runtime.
It can access class names, methods, fields, and constructors.
It belongs to the [Link] package.
Frameworks like Spring, Hibernate, and JUnit use reflection.

Reflection is powerful but can be slower.


It should be used carefully.

83. What is Serialization?


Serialization is the process of converting an object into a byte stream.
It is used to save an object to a file or send it over a network.
A class must implement the Serializable interface.
Serializable is a marker interface.
Serialization stores object state.

Top 100 Java Interview Questions and Answers Page 17


84. What is Deserialization?
Deserialization is the reverse process of serialization.
It converts a byte stream back into an object.
It is used to restore saved object state.

The class structure should match the serialized object.


Deserialization is commonly used in file handling, networking, and caching.

85. What is Singleton Design Pattern?


Singleton is a design pattern that allows only one object of a class.
It is used when only one instance should exist.
Examples include configuration, logging, and database connection manager.
The constructor is made private.
A static method returns the single instance.
class Singleton {
private static Singleton obj = new Singleton();

private Singleton() {
}

public static Singleton getInstance() {


return obj;
}
}

86. What is Factory Pattern?


Factory Pattern is a creational design pattern.
It is used to create objects without exposing object creation logic.
The client asks the factory for an object.
The factory decides which object to create.

It improves loose coupling.


It is useful when object creation logic is complex.

Coding and Tricky Questions


87. Difference between == and equals()?
== compares primitive values directly.
For objects, == compares references.

equals() compares object content when implemented properly.


In String, equals() compares actual text.
For object value comparison, prefer equals().

88. Difference between final, finally, and finalize()?


final is a keyword.
It can be used with variables, methods, and classes.
A final variable cannot be changed.

A final method cannot be overridden.

Top 100 Java Interview Questions and Answers Page 18


A final class cannot be inherited.
finally is a block used in exception handling.
finalize() was a method called before garbage collection, but it is deprecated and should not be used.

89. Can we overload the main method?


Yes, we can overload the main method in Java.
We can create multiple main methods with different parameters.
But JVM calls only the standard main method.
The standard signature is public static void main(String[] args).
Overloaded main methods must be called manually.

90. Can we override a static method?


No, static methods cannot be overridden.
Static methods belong to the class, not to objects.
If a child class defines a static method with the same signature, it is called method hiding.

Method overriding depends on runtime object behavior.


Static method calls are resolved at compile time.

91. Can we override a private method?


No, private methods cannot be overridden.
Private methods are not visible outside the class.
They are not inherited by child classes.
If a child class defines a method with the same name, it is a new method.
It is not overriding.

92. Can we inherit a final class?


No, a final class cannot be inherited.
The final keyword prevents inheritance.
It is used when we do not want a class to be extended.
For example, String is a final class.
This helps protect class behavior from modification.

93. Why is String immutable?


String is immutable to improve security, memory efficiency, and thread safety.
String Pool works safely because String values cannot change.
Immutable Strings can be shared between multiple references.

They are safe in multithreaded environments.


They are also useful in class loading, file paths, and network connections.

94. What happens when an object becomes null?


When a reference is set to null, it no longer points to the object.
If no other reference points to that object, it becomes eligible for garbage collection.
The object is not destroyed immediately.

The garbage collector removes it later when required.

Top 100 Java Interview Questions and Answers Page 19


Using a null reference can cause NullPointerException.

95. Difference between Heap and Stack memory?


Stack stores method calls, local variables, and references.
Heap stores objects.
Each thread has its own stack.
Heap is shared among all threads.
Stack memory is faster.
Heap memory is managed by garbage collector.
Stack memory is cleared when method execution completes.

96. What is Garbage Collection?


Garbage Collection is the automatic process of removing unused objects.
It is handled by the JVM.
Objects with no active references become eligible for garbage collection.

It mainly works on heap memory.


It helps free memory.
Developers can request garbage collection using [Link](), but JVM may ignore it.

97. What is Object Cloning?


Object cloning means creating an exact copy of an object.
Java provides the clone() method in the Object class.
The class should implement the Cloneable interface.
By default, cloning creates a shallow copy.
Cloning is used when we need a duplicate object with the same state.

98. Shallow Copy vs Deep Copy?


Shallow copy copies the object and its field values.
If the object has references, only the references are copied.
So both objects may share nested objects.
Deep copy copies the object and also creates copies of nested objects.
Deep copy is safer when objects contain mutable reference fields.

Shallow copy is faster but less independent.

99. Why is Java not 100% object-oriented?


Java is not 100% object-oriented because it uses primitive data types.

Primitive types like int, char, and boolean are not objects.
They are used for performance and memory efficiency.
Java also has wrapper classes like Integer and Character.
Because primitives are not objects, Java is not considered purely object-oriented.

100. Why are Strings immutable in Java?


Strings are immutable so their values cannot be changed after creation.

This improves security because Strings are used in sensitive places.

Top 100 Java Interview Questions and Answers Page 20


It improves memory usage through String Pool.
It makes Strings thread-safe.
It allows String hash codes to be cached.
Because of immutability, Strings are reliable and efficient in Java.

Top 100 Java Interview Questions and Answers Page 21

You might also like