OOPs :
1. Explain what object-oriented programming is?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept
of objects that contain data (fields) and behavior (methods). It focuses on designing
software that closely represents real-world entities.
OOP helps in creating reusable, secure, and maintainable applications.
Abstraction: Abstraction in Java is the process of hiding implementation details
and showing only the essential features of an object.
Example: An ATM or a coffee machine represents abstraction, where the user
interacts with simple operations while the internal working and implementation
details remain hidden.
Encapsulation Encapsulation in Java is an object-oriented principle that binds data
and methods into a single unit. It restricts direct access to data by using private
access modifier. This ensures controlled interaction with the data through getters and
setters methods.
Inheritance: Inheritance is a core OOP concept in Java that allows one class to
acquire the fields and methods of another class using the extends keyword.
Polymorphism: Polymorphism means “many forms”, where a single entity can
behave differently in different situations. In Java, it allows the same method or object
to show different behavior based on context.
Class: A Class in Java is a blueprint or template used to create objects. It defines the
properties (data) and behaviors (methods) that objects.
OBJECT : An Object in Java is an instance of a class that represents a real-world
entity. It is used to access the variables and methods defined inside a class.
2. What are the four pillars of OOP?
The main concepts of OOPs in Java are mentioned below:
Inheritance
Polymorphism
Abstraction
Encapsulation
3. Explain Inheritance with example.
Inheritance is a core Object-Oriented Programming (OOP) concept that allows a new
class (child/derived class) to acquire the properties and behaviors of an existing class
(parent/base class).
// Superclass
class Employee {
float salary = 40000;
void displaySalary() {
[Link]("Employee Salary: " +
salary);
}
}
// Subclass using 'extends'
class Developer extends Employee {
int bonus = 10000;
// Method Overriding (Common Interview Topic)
@Override
void displaySalary() {
[Link]("Developer Total: " +
(salary + bonus));
}
}
public class Main {
public static void main(String args[]) {
Developer dev = new Developer();
// Accessing field from superclass
[Link]("Base Salary: " +
[Link]);
// Accessing field from subclass
[Link]("Bonus: " + [Link]);
// Calling overridden method
[Link]();
}
}
4. Difference between Overloading and Overriding.
Overloading → Method Overloading in Java allows a class to have multiple methods
with the same name but different parameters, enabling compile-time polymorphism.
Overriding → Method overriding in Java allows a subclass to provide a specific
implementation of a method that is already defined in its parent class. It is one of the
key features of runtime polymorphism in object-oriented programming.
Method Overloading Method Overriding
When two or multiple methods are in the When a subclass provides its own
same class with different parameters but implementation of a method that is
the same name. already defined in the parent class.
Method overloading can only happen in
Method overriding can only happen in
the same class or between a subclass or
Subclass.
parent class.
When an error occurs it is caught at the When an error occurs it is caught at
compile time of the program. Runtime of the program.
Example of Compile Time
Example of Run Time Polymorphism.
Polymorphism.
Method Overloading may or may not Method overriding always needs
require Inheritance. Inheritance.
It is performed in two classes with an
It occurs within the class.
inheritance relationship.
Q: Can we overload the main() method?
Yes, but JVM always calls public static void main(String[] args) specifically.
Q. Can we change the scope of the overridden method in the subclass?
Yes, we can change the scope of an overridden method in the subclass, but only to make
it wider or the same as the superclass method’s scope.
If the overridden method in the superclass is public, the subclass method must be
public (it cannot be protected, default, or private).
If the overridden method in the superclass is protected, the subclass method can be
protected or public, but not private or default.
If the overridden method in the superclass has default (package-private) access, the
subclass method can be default, protected, or public, but not private.
A private method cannot be overridden because it is not visible to the subclass.
5. Difference between Abstract Class and Interface.
Abstract : A class declared as abstract, cannot be instantiated i.e., the object cannot be
created. It may or may not contain abstract methods but if a class has at least one
abstract method, it must be declared abstract.
Interface: An interface in Java is a collection of static final variables and abstract
methods that define the contract or agreement for a set of linked classes. Any class that
implements an interface is required to implement a specific set of methods. It specifies
the behavior that a class must exhibit but not the specifics of how it should be
implemented.
Abstract Class Interface Class
Both abstract and non-abstract methods The interface contains only abstract
may be found in an abstract class. methods.
The interface class does not support Final
Abstract Class supports Final methods.
methods.
Multiple inheritance is not supported by Multiple inheritances is supported by
the Abstract class. Interface Class.
Abstract Keyword is used to declare Interface Keyword is used to declare the
Abstract class. interface class.
extend keyword is used to extend an implements keyword is used to implement
Abstract Class. the interface.
Abstract Class has members like protected,
All class members are public by default.
private, etc.
6. Type of Inheritances?
Inheritance is the method by which the Child class can inherit the features of the
Super or Parent class. In Java, Inheritance is of four types:
Single Inheritance: When a child or subclass extends only one superclass, it is
known to be single inheritance. Single-parent class properties are passed down to
the child class.
Multilevel Inheritance: When a child or subclass extends any other subclass a
hierarchy of inheritance is created which is known as multilevel inheritance. In
other words, one subclass becomes the parent class of another.
Hierarchical Inheritance: When multiple subclasses derive from the same parent
class is known as Hierarchical Inheritance. In other words, a class that has a single
parent has many subclasses.
Multiple Inheritance: When a child class inherits from multiple parent classes is
known as Multiple Inheritance. In Java, it only supports multiple inheritance of
interfaces, not classes.
7. Explain Multiple Inheritance.
A component of the object-oriented notion known as multiple
inheritances allows a class to inherit properties from many parent
classes. When methods with the same signature are present in both
super classes and subclasses, an issue arises. The method's caller
cannot specify to the compiler which class method should be called or
even which class method should be given precedence .
Note: Java doesn’t support Multiple Inheritance
Q. What is the Diamond Problem?
When a class inherits from two classes that have the same
method, the compiler gets confused — "Which parent's method
should I call?" This ambiguity is called the Diamond Problem.
class A {
void show() { [Link]("A's show"); }
}
class B extends A {
void show() { [Link]("B's show"); }
}
class C extends A {
void show() { [Link]("C's show"); }
}
// ❌ COMPILE ERROR — Java won't allow this
class D extends B, C {
// Should D call B's show() or C's show() ??
}
8. Write code using inheritance and overriding.
// Base Class
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
void sound() {
[Link](name + " makes a sound");
}
void display() {
[Link]("Name: " + name);
sound(); // dynamic dispatch
}
}
// Child Class 1
class Dog extends Animal {
Dog(String name) { super(name); }
@Override
void sound() { [Link](name + " says:
Woof"); }
}
// Child Class 2
class Cat extends Animal {
Cat(String name) { super(name); }
@Override
void sound() { [Link](name + " says:
Meow"); }
}
// Main
public class Main {
public static void main(String[] args) {
// Normal call
Dog d = new Dog("Bruno");
Cat c = new Cat("Kitty");
[Link]();
[Link]();
// Polymorphism
Animal[] animals = { d, c };
for (Animal a : animals) {
[Link](); // runtime decides which
sound()
}
}
}
9. Difference between Class and Object.
Class → A blueprint/template that defines properties and behaviors. It occupies no
memory by itself.
Object → A real-world instance of a class. It occupies memory when created.
Class: In Java, Classes are the collection of objects sharing similar characteristics and
attributes. Classes represent the blueprint or template from which objects are created.
Classes are not real-world entities but help us to create objects which are real-world
entities.
OBJECT : The object is a real-life entity that has certain properties and methods
associated with it. The object is also defined as the instance of a class. An object can be
declared using a new keyword.
[Link] is a Constructor?
Constructor is a special method that is used to initialize objects. Constructor is called
when a object is created. The name of constructor is same as of the class.
There are two types of constructors in Java as mentioned below:
1. Default Constructor
2. Parameterized Constructor
Default Constructor: It is the type that does not accept any parameter value. It is
used to set initial values for object attributes.
class_Name(){}
// Default constructor called
Parameterized Constructor: It is the type of constructor that accepts parameters as
arguments. These are used to assign values to instance variables during the initialization
of objects.
class_Name(parameter1, parameter2, ......) {}
// All the values passed as parameter will be allocated
accordingly
Copy Constructor : The copy constructor is the type of constructor in which we pass
another object as a parameter because which properties of both objects seem the same,
that is why it seems as if constructors create a copy of an object.
[Link] are Access Specifiers?
Access Specifiers in Java help to restrict the scope of a class, constructor, variable,
method, or data member. There are four types of Access Specifiers in Java.
1. Public
2. Private
3. Protected
4. Default
Specifier Same Class Same Package Subclass (different package) Everywhere
private ✅ ❌ ❌ ❌
default (no keyword) ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅
[Link] is this keyword?
In Java, this is a keyword that refers to the current object, the object whose method or
constructor is being executed.
13. What is the use of super keyword?
The super keyword in Java is used to refer to the immediate parent class object in an
inheritance hierarchy. It allows a subclass to explicitly access parent class members when
they are hidden or overridden. This keyword helps maintain clarity and control while
working with inheritance.
Used to call parent class constructors using super().
Helps access parent class methods and variables when overridden or hidden.
Ensures proper inheritance behavior and code reusability.
14. Difference between Static and this keyword?
The this keyword refers to the current class object and is used to access current class
variables, methods, and constructors.
The super keyword in Java is used to refer to the immediate parent class object. It is mainly
used in inheritance to access parent class variables, methods, and constructors.
[Link] between static variable, method and class?
The static keyword in Java is used for memory management and
belongs to the class rather than any specific instance. It can be applied
to variables, methods, blocks, and nested classes to be shared among
all objects of a class.
static variables: static variables shared among all instances of the
class and is used to store data that should be common for all objects.
static method: A static method belongs to the class rather than to any
object. It can be called directly using the class name.
Can access only static data directly.
Cannot access instance variables or methods directly.
Cannot use this or super keywords.
// static variable
static int a = m1();
// static block
static{
[Link]("Inside static block");
}
// static method
static int m1(){
[Link]("From m1");
return 20;
}
static nested class: A static nested class is a class declared as static
inside another class. It can be accessed without creating an object of
the outer class.
class Outer {
static class Inner{
void show(){
[Link](
"Static Nested Class Method");
}
}
public static void main(String[] args)
{
[Link] obj = new [Link]();
[Link]();
}
}
Q. Can static methods be overloaded?
Yes, Static methods are overloaded. The method name is same, but number of parameters
or datatypes should be different.
Q. Can static methods be overridden?
No. Static methods belong to the class, not the object. It's called method hiding, not
overriding.
[Link] you explain final keyword in variable, method and class?
In Java, the final keyword is used to restrict changes and make code more
secure and predictable. It can be applied to variables, methods, and
classes to prevent modification, overriding, or inheritance. This helps in
creating constant values, stable methods, and immutable classes.
Final variable cannot be changed once assigned
Final method cannot be overridden
Final class cannot be inherited
[Link] public static void main(String args[]) in Java.
Unlike any other programming language like C, C++, etc. In Java, we
declared the main function as a public static void main (String args[]).
The meanings of the terms are mentioned below:
1. public: the public is the access modifier responsible for mentioning
who can access the element or the method and what is the limit. It
is responsible for making the main function globally available. It is
made public so that JVM can invoke it from outside the class as it is
not present in the current class.
2. static: static is a keyword used so that we can use the element
without initiating the class so to avoid the unnecessary allocation of
the memory.
3. void: void is a keyword and is used to specify that a method doesn’t
return anything. As the main function doesn't return anything we
use void.
4. main: main represents that the function declared is the main
function. It helps JVM to identify that the declared function is the
main function.
5. String args[]: It stores Java command-line arguments and is an
array of type [Link] class.
[Link] is Type Casting?
Type casting: Type casting in Java is a process used to convert a variable or value from one
data type to another.
Implicit Type casting (Widening): Widening casting is done automatically when passing a
smaller size type into a larger size type.
Flow: byte -> short -> char -> int -> long -> float -> double
Explicit Type casting (Narrowing): Narrowing casting is done manually when passing a larger
size type into a smaller size type.
Flow: double -> float -> long -> int -> char -> short -> byte
[Link] is Wrapper Classes? And Difference Between Autoboxing and
Unboxing?
A Wrapper class in Java is one whose object wraps or contains primitive data types
Autoboxing: The automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing.
For example: conversion of int to Integer, long to Long, double to Double, etc.
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of
a wrapper class to its corresponding primitive type is known as unboxing.
For example: conversion of Integer to int, Long to long, Double to double, etc.
20. Difference Between == and equals()
In Java, the equals() method and the == operator are used to compare objects. The main
difference is that string equals() method compares the content equality of two strings while
the == operator compares the reference or memory location of objects in a heap.
Exceptions:
[Link] to identify an exception
An exception can be identified by the exception type, message, and stack trace generated
during program execution. In Java, we can use try-catch blocks and methods like
getMessage(), getClass(), and printStackTrace() to determine the exact exception and its
cause.
try {
int result = 10 / 0;
} catch (Exception e) {
[Link]([Link]()); // Returns
exception message.
[Link]([Link]().getName()); //
Returns fully qualified exception name.
[Link]([Link]().getSimpleName());
// Returns exception name only.
[Link](); // Prints complete stack
trace.
}
[Link] is Exception and Exception Handling?
Exception: Exception is an event that occurs during program execution and disrupts the
normal flow of the program.
Exception Handling: Exception Handling in Java is a mechanism used to handle both
compile-time (checked) and runtime (unchecked) exceptions, allowing a program to
continue execution smoothly even in the presence of errors.
23. Difference Between throw and throws?
throw: The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception. The throw keyword
is mainly used to throw custom exceptions.
throws: throws is a keyword in Java that is used in the signature of a method to indicate that
this method might throw exceptions. The caller to these methods has to handle the
exception using a try-catch block.
public class Main {
static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]([Link]());
}
}
}
[Link] Between Checked Exceptions and Unchecked Exceptions
Checked exceptions: Checked exceptions are exceptions that are checked by the compiler at
compile time. If a method can throw a checked exception, it must be either handled using a
try-catch block or declared using the throws keyword.
Ex: IOException, InterruptedException, SQLException,
ClassNotFoundException , FileNotFoundException
public static void main(String[] args) throws
IOException {
// Getting the current root directory
String root = [Link]("[Link]");
// Adding the file name to the root directory
String path = root + "\\[Link]";
[Link]("File path: " + path);
// Reading the file from the path in the local
directory
try {
FileReader f = new FileReader(path);
// Creating an object as one of the ways of
taking input
BufferedReader b = new BufferedReader(f);
// Printing the first 3 lines of the file
for (int counter = 0; counter < 3; counter+
+)
[Link]([Link]());
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found: " +
[Link]());
} catch (IOException e) {
[Link]("An I/O error occurred:
" + [Link]());
}
}
Unchecked Exceptions: Unchecked exceptions are exceptions that are not checked by the
compiler at compile time. They occur during program execution and usually result from
programming errors or incorrect logic.
Ex: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
NumberFormatException, StringIndexOutOfBoundsException
[Link] final, finally, finalize have same functions?
final: final is a keyword is used with the variable, method, or class so that they can't be
overridden.
Example:
import [Link].*;
// Driver Class
class GFG {
// Main function
public static void main(String[] args)
{
final int x = 100;
x = 50;
}
}
Output:
./[Link]: error: cannot assign a value to final variable x
x=50;
1 error
Finally: finally is a block of code used with "try-catch" in exception handling. Code written
in finally block runs despite the fact exception is thrown or not.
Example:
import [Link].*;
// Driver class
class GFG {
// Main function
public static void main(String[] args)
{
int x = 10;
// try block
try {
[Link]("Try block");
}
// finally block
finally {
[Link](
"Always runs even without exceptions");
}
}
}
Output
Try block
Always runs even without exceptions
iii). Finalize: It is a method that is called just before deleting/destructing the objects which
are eligible for Garbage collection to perform clean-up activity.
Example:
import [Link].*;
class GFG {
public static void main(String[] args)
{
[Link]("Main function running");
[Link]();
}
// Here overriding finalize method
public void finalize()
{
[Link]("finalize method
overridden");
}
}
Output
Main function running
Collections in Java:
26. What is Collection in java?
A collection in Java refers to a group of objects treated as a single unit.
The Java Collection Framework provides a set of interfaces and classes that help store,
manipulate, and process groups of objects efficiently.
Collections is a utility class present in [Link] package. It defines several utility methods like
sorting and searching which is used to operate on collection Object.
Ex: [Link](), .addAll() ….
27. What is Generics?
Generics in Java refer to parameterized types that allow writing code which works with
multiple data types using a single class, interface, or method. They improve reusability and
ensure type safety at compile time.
[Link] Between Collection and Collections?
A collection in Java refers to a group of objects treated as a single unit.
Collections is a utility class present in [Link] package. It defines several utility methods like
sorting and searching which is used to operate on collection Object.
29. Difference Between arrays and collections?
Arrays are fixed in size that is once we create an array we can’t increase or decrease based
on our requirements. And Arrays can hold only homogeneous data types elements.
The collection is growable in nature and is based on our requirements. We can increase or
decrease of size. And Collection can hold both homogeneous and heterogeneous elements.
30. Difference Between Array List and LinkedList?
ArrayList is a class in Java Collections Framework that stores elements
in a sequential manner and automatically grows in size when needed. It
is widely used for fast data retrieval and managing ordered collections of
elements.
LinkedList is a class in Java Collections Framework that stores elements as interconnected
nodes instead of a continuous memory structure. It is mainly used when frequent insertion
and deletion operations are required.
31. Difference Between single LinkedList and Doubly LinkedList?
A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The
'data' field stores actual piece of information and 'link' field is used to point to (address of)
next node. The traversal is possible in one direction only.
A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
together with next pointer and data which are there in singly linked list. The traversal is
possible in both forward and backward directions.
32. Difference Between Array List and Vector?
The major difference between ArrayList and Vector is that ArrayList is not synchronized and
is therefore faster, whereas Vector is synchronized, making it thread-safe but slower due to
the overhead of synchronization.
33. Difference Between List and Set?
A List in Java is an ordered collection that allows duplicate elements and maintains the
insertion order of elements. It is part of the Java Collection Framework and provides
positional access to elements.
A Set in Java is a collection that does not allow duplicate elements and is used when
uniqueness of data is required. It is part of the Java Collection Framework and does not
maintain insertion order except LinkedHashSet.
34. Difference Between Queue and Stack?
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This
means that the last element added to the stack is the first one to be removed.
A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This
means that the first element added to the queue is the first one to be removed.
35. Difference Between HashMap and HashSet?
HashMap and HashSet are part of the Java Collection Framework used for efficient data
storage and retrieval.
HashMap is a data structure that stores elements in key-value pairs, where each key is
unique and maps to a value. It is widely used when we need to associate one value with
another.
HashSet is a collection that stores only unique elements and does not allow duplicates.
36. Difference Between HashMap and LinkedHashMap?
37. Difference Between HashMap and Hashtable?
38. Difference Between TreeMap and TreeSet?
TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed
and objects are stored in sorted and ascending order.
A TreeMap in Java is a part of the [Link] package that implements the Map interface. It
stores key-value pairs in a sorted order using either a natural or custom comparator.
[Link] Between iterator and ListIterator?
Iterator and ListIterator are interfaces provided by the Java Collection Framework to traverse
collection elements one by one. Iterator is used for simple forward traversal of collections
like List, Set, and Queue, whereas ListIterator provides advanced features such as backward
traversal, element modification, and insertion in List collections.
40. Difference Between iterator and Enumeration?
Iterator is used for simple forward traversal of collections like List, Set, and Queue, and even
classes implementing the Map interface. It provides methods to read and remove elements
from a collection during iteration.
Enumeration is an older interface used for traversing legacy collections such as Vector and
Hashtable. It allows you to read elements from these collections but does not support
modifications.
41. Difference Between Comparable and Comparator?
In Java, both Comparable and Comparator interfaces are used for sorting objects. The main
difference between Comparable and Comparator is:
Comparable: Comparable is used to define the natural ordering of the objects within
the class.
Comparator: Comparator is used to define custom sorting logic externally.
Threads:
[Link] is Multithreading?
Multithreading in Java is a feature that enables a program to run multiple threads
simultaneously, allowing tasks to execute in parallel and utilize the CPU more efficiently.
A thread is a lightweight, independent unit of execution inside a program (process).
A Java thread is the smallest unit of execution within a program. It is a lightweight
subprocess that runs independently but shares the same memory space as the process,
allowing multiple tasks to execute concurrently.
1. By Extending Thread Class :
We create a class that extends Thread and override its run() method to define the task.
Then, we make an object of this class and call start(), which automatically calls run() and
begins the thread’s execution.
class MyThread extends Thread{
// initiated run method for Thread
public void run(){
String str = "Thread Started Running...";
[Link](str);
}
}
public class Geeks{
public static void main(String args[]){
MyThread t1 = new MyThread();
[Link]();
}
}
2. Using Runnable Interface:
We create a new class which implements [Link] interface and define the run()
method there. Then we instantiate a Thread object and call start() method on this object.
class MyThread implements Runnable{
// Method to start Thread
public void run(){
String str = "Thread is Running Successfully";
[Link](str);
}
public class Geeks{
public static void main(String[] args){
MyThread g1 = new MyThread();
// initializing Thread Object
Thread t1 = new Thread(g1);
// Running Thread
[Link]();
}
}
[Link] Life of a Thread?
The lifecycle of a thread in Java defines the various states a thread goes
through from its creation to termination. Understanding these states
helps in managing thread behavior and synchronization in multithreaded
applications.
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Whenever a Thread Object is created it will be in new/born state. If start() is invoked it
enters into Ready or Runnable state. In this state the Thread is ready to execute run() but
waiting for Thread Scheduler to allocate processer. Whenever Thread Scheduler to allocate
processor. Whenever Thread Scheduler allocate processor it enters into Running State.
In running state it will be executing run(). If execution of run() is over then it enters into
Dead State.
While executing run(), due to some interruption from running state it may enter into waiting
state.
44. Difference Between Thread class and Runnable Interface?
The Thread class and Runnable interface Both approaches achieve the same goal, but they
differ in design flexibility, scalability, and best practices in real-world applications.
In a Thread Class Cannot extend any other class because Java allows single inheritance only
and Leads to tighter coupling.
In Runnable Interface Allows extending another class and Promotes abstraction and loose
coupling.
45. Difference Between Callable Interface and Runnable Interface?
Callable interface and Runnable interface are used to encapsulate tasks supposed to be
executed by another thread.
In a callable interface that basically throws a checked exception and returns some results.
This is one of the major differences between Runnable interface where no value is being
returned. In this interface, it simply computes a result else throws an exception if unable to
do so.
// Implementing the Callable interface
class CallableMessage implements Callable<String>{
public String call() throws Exception{
return "Hello World!";
}
}
public class CallableExample{
static ExecutorService executor =
[Link](2);
public static void main(String[] args) throws
Exception{
// Creating and running runnable task using
Thread class
CallableMessage task = new CallableMessage();
// Creating and running runnable task using
Executor Service.
Future<String> message =
[Link](task);
[Link]([Link]().toString());
}
}
In Runnable interface When an object implementing this interface is used to create a
thread, starting the thread causes the object run method to be called in a separately
executing thread.
The general. contract of this run() method is that it may take any action whatsoever.
// Implementing the Runnable interface
class RunnableImpl implements Runnable {
public void run()
{
[Link]("Hello World from a different
thread than Main");
}
}
public class RunnableExample{
static ExecutorService executor =
[Link](2);
public static void main(String[] args){
// Creating and running runnable task using
Thread class
RunnableImpl task = new RunnableImpl();
Thread thread = new Thread(task);
[Link]();
// Creating and running runnable task using
Executor Service.
[Link](task);
}
}
46. Difference Between Thread sleep() and yield() and join()?
47. Difference Between wait() and join()?
48. Demonstrate a classic race condition with a shared counter. How can you
fix it using synchronized?
49. Explain about synchronization?
Synchronization is used to control the execution of multiple processes or threads so that
shared resources are accessed in a proper and orderly manner. It helps avoid conflicts and
ensures correct results when many tasks run at the same time.
Synchronized methods: Synchronized methods are used to lock an entire method so that
only one thread can execute it at a time for a particular object. This ensures safe access to
shared data but may reduce performance due to full method locking.
Synchronized blocks: Synchronized blocks allow locking only a specific section of code
instead of the entire method. This makes the program more efficient by reducing the scope
of synchronization.
Static synchronization: Static synchronization is used when static data or methods need to
be protected in a multithreaded environment. It ensures that only one thread can access the
class-level resource at a time.
50. Explain Deadlock?
Strings:
51. Explain Why String is Immutable?
A String in Java is an object used to store a sequence of characters enclosed in double
quotes.
String is immutable, which means that once a String object is created, its value cannot be
changed.
Strings are stored in a String Pool, allowing reuse of objects and reducing memory
overhead.
Multiple threads can safely share the same string object without synchronization.
[Link] is String Pool?
The Java String Pool is a special memory area inside the heap that stores string literals.
String Literals:
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
[Link](s1 == s2); // true
[Link]([Link](s2)); // true
}
Using new Keyword:
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("abc");
[Link](s1 == s2); // false
[Link]([Link](s2)); // true
}
public static void main(String[] args) {
String s1 = "abc";
String s2 = new String("abc");
[Link](s1 == s2); // false
[Link]([Link](s2)); // true
}
53. Difference Between String and StringBuffer and StringBulider?
String and StringBuffer and StirngBuilder are stores sequence of characters but differ in
mutability, present in [Link] package.
A String in java is an immuatable sequence of characters,creating string object. its value
cannot be changed.
StringBuffer class in Java represents a sequence of characters that can be mutable, without
creating a new object every time. All methods of StringBuffer are synchronized, making it
safe to use in multithreaded environments.
In Java, the StringBuilder class provides a mutable sequence of characters. StringBuilder
allows modification of character sequences without creating new objects, making it
memory-efficient and faster for frequent string operations. StringBuilder is not
synchronized, it performs better in single-threaded applications.
[Link] Between StringBuffer and StringBulider?
StringBuffer and StringBuilder are classes in Java used to create and
modify mutable strings. Unlike the String class, their content can be
changed without creating a new object.
StringBuffer is thread-safe and synchronized. It is designed for multi-threaded environments
where multiple threads may modify the same string object.
whereas StringBuilder is not synchronized and not thread-safe. It is optimized for single-
threaded environments where performance is critical.
Memory:
55. Difference Between Heap and Stack?
Stack Memory: Stores primitive local variables, method call information, and references to
objects during program execution.
Heap Memory: Stores actual objects and dynamic data allocated at runtime. Objects created
with new are placed here, and this memory is managed by the Garbage Collector.
[Link] Usage
[Link] you explain garbage collection in Java? What is the main object
of that?
In Java, Garbage collection is necessary to avoid memory leaks which can cause the program
to crash and become unstable. There is no way to avoid garbage collection in Java. Unlike C+
+, Garbage collection in Java helps programmers to focus on the development of the
application instead of managing memory resources and worrying about memory leakage.
Java Virtual Machine (JVM) automatically manages the memory periodically by running a
garbage collector which frees up the unused memory in the application. Garbage collection
makes Java memory efficient because it removes unreferenced objects from the heap
memory.
[Link] part of memory is cleaned in garbage collection? Is it stack or
heap?
Programs:
[Link] to program to print all the leaves of a binary tree?
class Node {
int data;
Node left, right;
Node(int data) {
[Link] = data;
left = right = null;
}
}
public class PrintLeaves {
// Function to print leaf nodes
static void printLeaves(Node root) {
// Base case
if (root == null)
return;
// If leaf node
if ([Link] == null && [Link] == null) {
[Link]([Link] + " ");
return;
}
// Traverse left subtree
printLeaves([Link]);
// Traverse right subtree
printLeaves([Link]);
}
public static void main(String[] args) {
/*
1
/ \
2 3
/ \ \
4 5 6
Leaf nodes: 4 5 6
*/
Node root = new Node(1);
[Link] = new Node(2);
[Link] = new Node(3);
[Link] = new Node(4);
[Link] = new Node(5);
[Link] = new Node(6);
[Link]("Leaf nodes are: ");
printLeaves(root);
}
}
[Link] to print all the permutations of a string? (All character array
permutations of a given string)
import [Link];
public class StringPermutations {
// Swap function
static String swap(String str, int i, int j) {
char[] arr = [Link]();
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return new String(arr);
}
// Recursive function
static void permute(String str, int left, int
right) {
// Base case
if (left == right) {
[Link](str);
return;
}
// To avoid duplicates
HashSet<Character> set = new HashSet<>();
for (int i = left; i <= right; i++) {
// Skip duplicate characters
if ([Link]([Link](i))) {
continue;
}
[Link]([Link](i));
// Swap
str = swap(str, left, i);
// Recursive call
permute(str, left + 1, right);
// Backtrack
str = swap(str, left, i);
}
}
public static void main(String[] args) {
String str = "AAB";
[Link]("Unique permutations:");
permute(str, 0, [Link]() - 1);
}
}
Java 8:
61. What are the features of Java 8?
Functional Interfaces
Lambda Expressions
Default and static methods in interfaces
Method References
Stream API
Optional
CompletableFuture
Date-time API
62. What is Functional Interface? Examples
An interface with only one abstract method. It can have default and static methods. It may
or may not be annotated with @FunctionalInterface. Few functional interfaces are
Runnable, Function, Consumer, Supplier.
[Link] functional interfaces?
To perform one single functionality. Consumer to consume data, Supplier to return data.
64. What is Method Reference in Java? How and when it is used?
[Link] is Streams API?
A Stream represents a sequence of elements and supports parallel and sequentional
operations. Streams are abstraction for processing of values.
66. What is optional class and its use?
67. Difference between [Link]() and [Link]()?
68. What are Memory leaks and how can they be avoided?
69. Can u add new methods to an existing interface?
70. Which Map implemention prevents memory leak?
71. Can you add two null values in HashMap?
72. How do you create threads in java?
73. Write a code to implement Runnable using lambda?
74. Explain the lifecycle of Thread?
When a thread is first created. It’s in the NEW state
Thread th = new Thread();
When you invoke start() method, it gets ready to get the CPU. [Link]()
The thread changes to RUNNABLE state depending on its priority.
When sleep/wait method is called on a RUNNABLE thread, it may enter the NOT
RUNNABLE state. [Link]();
When a thread is BLOCKED, it’s still alive, but it’s not eligiable for execution.
A BLOCKED thread becomes ready to run again when the sleeping thread wakes up.
This thread occupies the CPU depending on it’s PRIOROTY
When a thread terminates, it’s said to be DEAD.
75. Difference between Runnable and Callable?
76. What is ConcurrentModificationException?
This exception occurs when you try to modify your collection while iterating – fail fast
behaviour.
77. Explain Singleton Design Pattern?
This is a creational design pattern. It ensures that a class has only one instance / object all
though the application. Create a class with private constructor, public static method that
returns the object.
78. If I write return / [Link](0) statement inside try block will finally
block get executed?
79. Can we have a try block without catch and finally?
No. But if you are using try with resources, then yes. But you need to use throws declaration.
80. What are checked and unchecked exceptions? How do you handle using multiple catch
statements?