Java Interview Questions for 3 years Experience
Java Interview Questions for 3 Years of Experience
Preparing for a Java interview Questions for 3 Years of Experience can be challenging, especially with all the different topics that
could come up. If you have about three years of experience with Java, it’s important to be familiar with both basic and advanced
concepts. This article offers a helpful list of Java interview questions for Freshers, covering everything you need to know. By
practicing these questions, you’ll feel more confident and ready to show your skills in the interview.
Top 50 Java Interview Questions For 3 Years Experienced Candidates
Q 1. What are the main features of Java?
Java is a high-level, object-oriented, and platform-independent programming language. Its key features of Java include platform
independence, object orientation, robust memory management, exception handling, multithreading, and security features.
In this Interview tutorial, let's learn the top 50 Java interview questions for a 3 years' experience candidate. To further strengthen
your Java knowledge and enhance your interview preparation, consider enrolling in our Java Online Course Free With Certicate,
which offers comprehensive learning and certication to boost your career prospects.
Example
// Java Example: Platform Independence
public class HelloWorld {
}
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
Output
Output
Example
Hello, Java!
Car brand: Tesla, Speed: 200 km/h
// Java Example: Creating an Object
class Car {
String brand;
int speed;
} p u b l i c
c l a s s
O b j e c t E x a m p l
e {
void display() {
System.out.println("Car brand: " + brand + ", Speed: " + speed + " km/h");
}
}
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Tesla";
myCar.speed = 200;
myCar.display();
}
Q 3. What is an object in Java?
An object in Java is an instance of a class. It represents real-world entities with states (variables) and behaviors (methods). Objects
are the basic units that help organize and model real-world situations in a Java application.
Q 2. What is the difference between JDK, JRE, and JVM?
Q 4. What is the difference between abstraction and encapsulation in Java?
Users
Aspect
Purpose
Components
Try it Yourself >>
Try it Yourself >>
JDK (Java Development Kit) JRE (Java Runtime Environment)
Provides the runtime environment
for Java programs.
JVM (Java Virtual Machine)
Executes Java bytecode.
Provides
development.
Includes JRE, compiler, debugger,
and development tools.
Used by developers to write Java
programs.
tools for Java
Includes
required for execution.
Used by end-users to run Java
programs.
JVM and libraries Part of the JRE, performs execution
and memory management.
Used internally by JRE to execute code.
Try it Yourself >>
Aspect
Denition
Abstraction
Hides implementation details and shows only the
functionality.
Encapsulation
Hides the internal state of an object and protects it from
unauthorized access.
Focus
Implementation
Focuses on "what" the object does.
Achieved using abstract classes and interfaces.
Focuses on "how" the object's data is protected.
Achieved by declaring variables private and providing
getters and setters.
A constructor in Java is a special method that is used to initialize objects. It is called automatically when an object of a class is
created. It does not have a return type and has the same name as the class.
Output
Example
Example
Woof! Woof!
// Java Example: Abstraction and Encapsulation
abstract class Animal {
}
class Dog extends Animal {
abstract void sound();
}
public class AbstractionExample {
void sound() {
System.out.println("Woof! Woof!");
}
}
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
// Java Example: Constructor
class Car {
} p u b l i c c l a s s
C o n s t r u c t o r E x a
m p l e {
String brand;
// Constructor
Car(String brand) {
this.brand = brand;
}
v o i d d i s p l a y ( ) {
System.out.println("Car brand: " + brand);
}
Q 5. What is a constructor in Java?
Output
Output
Example
Example
Car brand: Tesla
Sum of integers: 15
Sum of doubles: 16.0
}
public static void main(String[] args) {
Car myCar = new Car("Tesla");
myCar.display();
}
// Java Example: Method Overloading
class Calculator {
} p u b l i c c l a s s
O v e r l o a d i n g E x a
m p l e {
int add(int a, int b) {
return a + b;
}
d o u b l e a d d ( d o u b l e a , d o u b l e b ) {
return a + b;
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of integers: " + calc.add(5, 10));
System.out.println("Sum of doubles: " + calc.add(5.5, 10.5));
}
Q 7. What is method overriding in Java?
Method overriding in Java occurs when a subclass provides a specic implementation for a method already dened in its
superclass. The overridden method in the subclass must have the same signature as the method in the superclass.
Q 6. What is method overloading in Java?
Method overloading in Java refers to dening multiple methods in a class with the same name but different parameters (either in
number or type). Overloading increases the readability of the program.
Try it Yourself >>
Try it Yourself >>
Output
Example
Dog barks
// Java Example: Method Overriding
class Animal {
}
class Dog extends Animal {
void sound() {
System.out.println("Animal makes a sound");
}
} p u b l i c c l a s s
O v e r r i d i n g E x a
m p l e {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
// Java Example: == vs equals()
class Person {
}
public class ComparisonExample {
String name;
Person(String name) {
this.name = name;
}
public static void main(String[] args) {
Person p1 = new Person("John"); Person p2 = new
Person("John"); System.out.println("Using ==: " + (p1 == p2)); //
false
Q 8. What is the difference between == and equals() in Java?
The "==" operator compares the memory addresses of two objects, i.e., whether the two references point to the same memory
location. The equals() method compares the actual content of the objects to check if they are logically equivalent.
Aspect
Comparison
Type
Default Behavior
Try it Yourself >>
== Operator
Compares references (memory location).
Used for primitives and references.
Compares memory locations by default.
equals() Method
Compares content of objects.
Used only for objects.
Compares object data; must be overridden in custom classes.
Output
Output
Example
Animal makes a sound
Dog barks
Using ==: false
Using equals(): true
// Java Example: super keyword
class Animal {
}
class Dog extends Animal {
void sound() {
System.out.println("Animal makes a sound");
}
} p u b l i c
c l a s s
S u p e r E x a m p l
e {
void sound() {
super.sound(); // Calling the parent class method
System.out.println("Dog barks");
}
}
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
}
System.out.println("Using equals(): " + p1.name.equals(p2.name)); // true
}
Q 9. What is the use of the super keyword in Java?
The super keyword in Java refers to the immediate parent class object. It is commonly used to access parent class methods and
constructors from the subclass.
Q 10. What is the difference between ArrayList and LinkedList in Java?
ArrayList and LinkedList both implement the List interface, but their internal structure and performance characteristics differ:
Aspect
Internal Structure
Try it Yourself >>
Try it Yourself >>
ArrayList
Backed by a dynamic array.
LinkedList
Backed by a doubly linked list.
Thread
Safety
Thread
Safety
Aspect
Immutability
Memory
Consumption
Access Speed
Insertion/Deletion
Try it Yourself >>
String
Immutable (cannot be changed after
creation).
Not thread-safe.
StringBuffer
Mutable (can be modied).
StringBuilder
Mutable (can be modied).
Thread-safe
methods).
Slower due to synchronization
overhead.
(synchronized Not thread-safe.
Slower due to immutability. Faster than StringBuffer due
synchronization.
to no
Faster access (O(1)) for indexed operations.
Slower insertion and deletion (O(n)) in the
middle.
Uses less memory compared to LinkedList.
Slower access (O(n)) due to traversal.
Faster insertion/deletion (O(1)) at both ends.
Consumes more memory due to extra references in each
node.
String, StringBuffer, and StringBuilder are used to represent strings in Java. The key differences lie in their mutability and thread
safety:
Output
Example
Example
ArrayList: [10, 20]
LinkedList: [30, 40]
// Java Example: ArrayList vs LinkedList
import java.util.*;
public class ListExample {
}
public static void main(String[] args) {
List arrayList = new ArrayList<>(); List linkedList =
new LinkedList<>(); arrayList.add(10);
arrayList.add(20); linkedList.add(30);
linkedList.add(40); System.out.println("ArrayList: " +
arrayList); System.out.println("LinkedList: " +
linkedList);
}
// Java Example: String vs StringBuffer vs StringBuilder
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
Q 11. What is the difference between String, StringBuffer, and StringBuilder?
Output
Output
Example
Woof
String: Hello World
StringBuffer: Hello World
StringBuilder: Hello World
// Java Example: Interface
interface Animal {
} class Dog implements Animal
{
void sound();
}
public class InterfaceExample {
public void sound() {
System.out.println("Woof");
}
}
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
str1 = str1 + " World";
StringBuffer buffer = new StringBuffer("Hello");
buffer.append(" World");
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World");
System.out.println("String: " + str1);
System.out.println("StringBuffer: " + buffer);
System.out.println("StringBuilder: " + builder);
}
}
Q 12. What is an interface in Java?
An interface in Java is a reference type similar to a class, but it can only contain constants, method signatures, default methods,
static methods, and nested types. Interfaces cannot contain instance elds or constructors. It is used to achieve abstraction and
multiple inheritance.
Try it Yourself >>
Try it Yourself >>
Q 13. What is the difference between Method Overloading and Method Overriding?
Method Overloading and Method Overriding are both used to achieve polymorphism, but they differ in how they are implemented and
used:
Aspect
Denition
Compile-Time
Run-Time
Inheritance
Return Type
Access Modier
Does not require inheritance.
It can have a different return type.
It can have different access modiers.
Requires inheritance or interface implementation.
It must have the same return type.
It must have the same or a more accessible access
modier.
Method Overloading
Dening multiple methods with the same name but
different parameter lists.
Occurs at compile-time (Static Polymorphism).
Method Overriding
Providing a new implementation for a method already
dened in the parent class.
Occurs at run-time (Dynamic Polymorphism).
vs
Let's learn the difference between Method Overloading and Method Overiding.
Example
// Java Example: Method Overloading vs Method Overriding
class Animal {
} c l a s s D o g
e x t e n d s
A n i m a l {
void sound() {
System.out.println("Animal makes a sound");
}
} p u b l i c c l a s s
O v e r l o a d O v e r r i d e
E x a m p l e {
// Overriding method
void sound() {
System.out.println("Dog barks");
}
/ / O v e r l o a d i n g m e t h o d
v o i d s o u n d ( S t r i n g s o u n d T y p e ) {
System.out.println("Dog " + soundType);
}
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Calls parent method
Dog dog = new Dog();
dog.sound(); // Calls overridden method
Output
Output
Example
Example
Name: John
Animal makes a sound
Dog barks
Dog whines
}
dog.sound("whines"); // Calls overloaded method
}
// Java Example: this keyword
class Person {
} p u b l i c c l a s s
T h i s K e y w o r d E x a
m p l e {
String name;
Person(String name) {
this.name = name; // 'this' refers to the current object's instance variable
}
v o i d d i s p l a y ( ) {
System.out.println("Name: " + this.name); // 'this' used to refer to current object's field
}
}
public static void main(String[] args) {
Person person = new Person("John");
person.display();
}
Q 15. What are Java Collections?
Java Collections framework provides a set of classes and interfaces that implement commonly used collection data structures. The
Collections framework includes the following interfaces: List, Set, Queue, and Map, each with various implementations like ArrayList,
HashSet, LinkedList, PriorityQueue, and HashMap.
Q 14. What is the use of 'this' keyword in Java?
The "this" keyword in Java is used to refer to the current object of the class. It helps distinguish between instance variables and local
variables when they have the same name, and it is also used to call one constructor from another constructor in the same class.
Try it Yourself >>
Try it Yourself >>
Output
Example
List: [Apple, Banana]
Set: [Apple, Banana]
Map: {1=Apple, 2=Banana}
// Java Example: Constructor
class Car {
String model;
// Constructor
Car(String model) {
this.model = model;
}
// Set implementation
Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
// Map implementation
Map map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
}
System.out.println("List: " + list);
System.out.println("Set: " + set);
System.out.println("Map: " + map);
}
// Java Example: Collections Framework
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// List implementation
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
void display() {
System.out.println("Car model: " + this.model);
}
Q 16. What is a constructor in Java?
A constructor in Java is a special method used to initialize objects in Java. It is called when an object of a class is created, and it is
used to set the initial values for the object's instance variables.
Try it Yourself >>
Output
Example
Car model: Tesla
}
public class ConstructorExample {
}
public static void main(String[] args) {
Car car = new Car("Tesla");
car.display();
}
// Java Example: final, finally, finalize
class MyClass {
}
public class FinalExample {
final int x = 10;
void display() {
System.out.println("Value of x: " + x);
}
/ / f i n a l i z e m e t h o d
protected void finalize() {
System.out.println("Object is being garbage collected");
}
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
obj = null; // eligible for garbage collection
System.gc(); // Requesting garbage collection
}
Q 17. What is the difference between nal, nally, and nalize in Java?
nal, nally, and nalize are different concepts in Java:
Try it Yourself >>
Execution Executed at compile-time.
Aspect
Denition
nal Used to dene constants,
prevent
prevent
method
inheritance.
overriding, or
Usage It
methods, or classes.
can be applied to variables,
nally Used to dene a block of code that
will
always execute, regardless of exception
handling. Used in exception handling
blocks (try-
catch-nally).
nalize
Used to perform cleanup before an
object is garbage collected.
Called by the garbage collector
when the object is ready for a
cleanup. Called by garbage
collector, not
guaranteed to be called.
Executed at runtime, always after the try-
catch block.
Output
Output
Example
Hello World
Hello World
Value of x: 10
Object is being garbage collected
}
StringBuffer sf = new StringBuffer("Hello");
sf.append(" World");
System.out.println(sf);
}
// Java Example: StringBuilder vs StringBuffer
public class StringBuilderBufferExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
Q 19. What is the purpose of the static keyword in Java?
The static keyword in Java is used for memory management. It is applied to variables, methods, blocks, and nested classes. Static
members belong to the class rather than instances, meaning they can be accessed without creating an object of the class. Static
variables are shared among all instances of a class, and static methods can be invoked without creating an object.
Q 18. What is the difference between StringBuilder and StringBuffer in Java?
StringBuilder and StringBuffer are both used for creating mutable strings, but the main difference between them is that StringBuffer
is synchronized, making it thread-safe, while StringBuilder is not. Therefore, StringBuffer is slower than StringBuilder.
Aspect
Thread Safety
Performance
Use Case
Methods
Try it Yourself >>
Try it Yourself >>
StringBuilder
Not thread-safe (faster).
Faster because it is not synchronized.
Used when thread safety is not required.
Uses methods like append(), insert(), delete(), etc.
StringBuffer
Thread-safe (slower).
Slower due to synchronization.
Used when thread safety is required.
Same methods as StringBuilder but synchronized.
Output
Example
Example: Creating and Using a Custom Annotation
Count: 2
// Java Example: Custom Annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
// Step 1: Define the custom annotation
@Retention(RetentionPolicy.RUNTIME) // Retain at runtime
@Target(ElementType.METHOD)
@interface MyAnnotation {
// Apply only to methods
} // Step 2: Annotate methods with the custom annotation
class MyClass {
String value() default "Default Message";
@MyAnnotation(value = "Hello, World!")
public void myMethod() {
System.out.println("Executing myMethod()");
}
@MyAnnotation
// Java Example: Static Keyword
class Counter {
} p u b l i c c l a s s
S t a t i c K e y w o r d E x
a m p l e {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public static void main(String[] args) {
Counter c1 = new Counter(); Counter c2 = new Counter();
Counter.displayCount(); // Accessing static method without object
}
Q 20. What are Java annotations, and how are custom annotations created?
Try it Yourself >>
Annotations in Java are metadata that provide additional information about the code. They do not affect the code execution
directly but are used by the compiler or during runtime to perform certain tasks such as code analysis or processing. Common
built-in annotations include ̀`@Override`, ̀`@Deprecated`, and ̀`@SuppressWarnings`.
Custom annotations can also be created to dene specic metadata for your application. They are dened using the `@interface`
keyword and can include elements (like methods) to specify additional values.
Output
Example
Method: myMethod
Annotation Value: Hello, World!
Executing myMethod()
Method: anotherMethod
Annotation Value: Default Message
Executing anotherMethod()
// Java Example: Observer Design Pattern
import java.util.*;
interface Observer {
}
class ConcreteObserver implements Observer {
void update(String message);
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
// Step 3: Access the annotation using reflection
public class AnnotationExample {
public void anotherMethod() {
System.out.println("Executing anotherMethod()");
}
}
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method[] methods = obj.getClass().getDeclaredMethods();
for (Method method : methods) {
// Check if MyAnnotation is present
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Method: " + method.getName());
System.out.println("Annotation Value: " + annotation.value());
method.invoke(obj); // Call the method
System.out.println();
}
}
}
Q 21. What is the Observer Design Pattern in Java?
The Observer Design Pattern is a behavioral pattern where an object (subject) maintains a list of dependent objects (observers) that
are notied of any state changes. This pattern is typically used in scenarios where an object needs to update other objects
automatically when its state changes without tight coupling between the objects.
Try it Yourself >>
Output
Observer1 received message: State Changed!
Observer2 received message: State Changed!
}
class Subject {
}
@ O v e r r i d e
p u b l i c v o i d u p d a t e ( S t r i n g m e s s a g e ) {
System.out.println(name + " received message: " + message);
}
} p u b l i c c l a s s
O b s e r v e r P a t t e r n E
x a m p l e {
private List observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
p u b l i c v o i d r e m o v e O b s e r v e r ( O b s e r v e r o b s e r v e r ) {
observers.remove(observer);
}
p u b l i c v o i d n o t i f y O b s e r v e r s ( S t r i n g m e s s a g e ) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
public static void main(String[] args) {
// Create subject and observers Subject subject = new
Subject(); Observer observer1 = new
ConcreteObserver("Observer1");
Observer observer2 = new ConcreteObserver("Observer2");
// Register observers
subject.addObserver(observer1);
subject.addObserver(observer2);
// Notify all observers
subject.notifyObservers("State Changed!");
}
Q 22. What is the difference between `wait()` and `sleep()` methods in Java?
The `wait()` and `sleep()` methods are both used to pause the execution of a thread, but they have signicant differences in terms of
their behavior and usage:
Try it Yourself >>
wait(): The `wait()` method is used in multithreading and is called on an object’s monitor (lock). It makes the current thread
release the lock and enter the waiting state until another thread sends a notification via ̀`notify()` or ̀`notifyAll()`. This method must
be called inside a synchronized block or method.
sleep(): The `sleep()` method is a static method of the `Thread` class that makes the current thread sleep for a specied number
of milliseconds, without releasing any locks. It simply pauses the thread’s execution for the given time period, and does not
require synchronization.
Output
Example
Example
Thread 13 is going to wait.
Thread 1 is going to sleep.
Thread 1 woke up. Thread 13
resumed.
public class ExceptionExample {
// Java Example: Checked vs Unchecked Exceptions
import java.io.*;
// Java Example: wait() vs sleep()
class WaitExample extends Thread {
} p u b l i c c l a s s
S l e e p W a i t E x a m
p l e {
public void run() {
synchronized (this) {
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is going to wait.");
wait(5000); // Thread waits for 5 seconds
System.out.println("Thread " + Thread.currentThread().getId() + " resumed.");
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) throws InterruptedException {
// Using wait() method
WaitExample t1 = new WaitExample();
t1.start();
// Using sleep() method
System.out.println("Thread " + Thread.currentThread().getId() + " is going to sleep.");
Thread.sleep(3000); // Main thread sleeps for 3 seconds
System.out.println("Thread " + Thread.currentThread().getId() + " woke up.");
}
}
Q 23. What are the different types of exceptions in Java?
Exceptions in Java are categorized into two main types:
Try it Yourself >>
Checked Exceptions: These are exceptions that are checked at compile-time. Examples include FileNotFoundException,
SQLException, etc. These exceptions must be handled using a try-catch block or declared using the throws keyword.
Unchecked Exceptions: These are exceptions that occur at runtime. Examples include ArithmeticException,
NullPointerException, etc. These do not need to be handled explicitly.
Output
Example
Checked Exception: File not found.
Unchecked Exception: Cannot divide by zero.
// Java Example: finally Block
public class FinallyExample {
}
public static void main(String[] args) {
try {
System.out.println("Inside try block");
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught in catch block");
} finally {
System.out.println("Finally block executed");
}
}
public static void main(String[] args) {
try {
// Checked Exception: FileNotFoundException
File file = new File("nonexistentfile.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("Checked Exception: File not found.");
}
}
// Unchecked Exception: ArithmeticException
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Unchecked Exception: Cannot divide by zero.");
}
}
Q 24. What is the purpose of the nally block in Java?
The nally block in Java is used to execute a block of code after a try-catch block, regardless of whether an exception was thrown or
not. It is typically used for closing resources such as le streams or database connections.
Try it Yourself >>
Try it Yourself >>
Output
Example
Inside try block
Exception caught in catch block
Finally block executed
// Java Example: Factory Design Pattern
interface Animal {
} class Dog implements Animal
{
void makeSound();
} class Cat implements Animal {
public void makeSound() {
System.out.println("Woof");
}
} / /
F a c t o r y
C l a s s
class AnimalFactory {
public void makeSound() {
System.out.println("Meow");
}
}
public class FactoryPatternExample {
public static Animal getAnimal(String type) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("Dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("Cat")) {
return new Cat();
}
return null;
}
public static void main(String[] args) {
// Creating objects using Factory Method
Animal dog = AnimalFactory.getAnimal("Dog");
dog.makeSound(); // Output: Woof
}
Animal cat = AnimalFactory.getAnimal("Cat");
cat.makeSound(); // Output: Meow
}
Q 25. What is the Factory Design Pattern in Java?
The Factory Design Pattern is a creational design pattern used to create objects without specifying the exact class of object that will
be created. The Factory method allows the creation of objects based on a particular type or condition, abstracting the instantiation
process from the client code.
Output
Output
Example
Example
Wo
of
Meo
w
Result of addition: 8
// Java Example: transient Keyword
import java.io.*;
class Employee implements Serializable {
int id;
String name;
transient String password; // transient variable
public Employee(int id, String name, String password) {
this.id = id;
// Java Example: Lambda Expression
interface MathOperation {
} public class LambdaExample
{
int operate(int a, int b);
}
public static void main(String[] args) {
MathOperation add = (a, b) -> a + b;
System.out.println("Result of addition: " + add.operate(5, 3));
}
Q 26. What is a Lambda Expression in Java?
A Lambda expression in Java is a short block of code that takes in parameters and returns a value. Lambda expressions are used
primarily to dene the behavior of methods in functional programming interfaces. Lambda expressions enable the use of methods
as arguments in functional programming.
Q 27. What is the use of the transient keyword in Java?
The transient keyword in Java is used to mark a variable as not to be serialized. If a eld is marked as transient, its value will not be
included in the serialization process, which is particularly useful for sensitive information such as passwords.
Try it Yourself >>
Try it Yourself >>
Output
Example
Employee ID: 101
Employee Name: John
Employee Password: null
// Java Example: Singleton Design Pattern
class Singleton {
private static Singleton instance;
// Private constructor prevents instantiation from other classes
private Singleton() {}
// Static method to get the instance of the class
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
r e t u r n i n s t a n c e ;
}
public class TransientKeywordExample {
this.name = name;
this.password = password;
}
}
public static void main(String[] args) throws IOException {
Employee emp = new Employee(101, "John", "password123");
// Serialization
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
// Deserialization
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee deserializedEmp = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Employee ID: " + deserializedEmp.id);
System.out.println("Employee Name: " + deserializedEmp.name);
System.out.println("Employee Password: " + deserializedEmp.password); // will be null
}
Q 28. What is the Singleton Design Pattern in Java?
The Singleton design pattern in Javaensures that a class has only one instance and provides a global point of access to that
instance. It is useful when you need to control access to shared resources, such as database connections or conguration settings.
Try it Yourself >>
Output
Example
Singleton Instance: Singleton@5f150435
Singleton Instance: Singleton@5f150435
// Java Example: HashSet vs TreeSet
import java.util.*;
public class SetExample {
public static void main(String[] args) {
// HashSet Example
Set hashSet = new HashSet<>();
hashSet.add("Banana");
hashSet.add("Apple");
System.out.println("HashSet: " + hashSet);
// TreeSet Example
Set treeSet = new TreeSet<>();
treeSet.add("Banana");
treeSet.add("Apple");
System.out.println("TreeSet: " + treeSet);
}
p u b l i c v o i d d i s p l a y ( ) {
System.out.println("Singleton Instance: " + this);
public static void main(String[] args) {
}
Singleton singleton1 = Singleton.getInstance();
singleton1.display();
Singleton singleton2 = Singleton.getInstance();
singleton2.display();
}
Q 29. What is the difference between HashSet and TreeSet in Java?
HashSet and TreeSet are both part of the Set interface in Java, but they differ in their internal data structure and behavior:
Aspect
Ordering
Null
Elements
Sor ting
Performance
Try it Yourself >>
Does not guarantee sorting. Automatically sorts the elements.
HashSet
No ordering, elements are stored in an unordered
fashion.
Faster for operations like add, remove, and
contains (O(1)).
TreeSet
Maintains a natural ordering or a custom order based on a
comparator.
Slower due to the need to maintain order (O(log n)).
Allows null elements. Does not allow null elements.
Output
Output
Example
Example: Using HashMap and ConcurrentHashMap
Key Differences between ̀`HashMap` and ̀`ConcurrentHashMap`
}
}
HashSet: [Apple, Banana]
TreeSet: [Apple, Banana]
// Compile-time error: variable number might not have been initialized
// Java Example: Default Value of Local Variable
public class LocalVariableExample {
public static void main(String[] args) {
// Local variable (uninitialized)
int number;
// System.out.println(number); // Uncommenting this will give a compile-time error
}
}
Q 30. What is the default value of a local variable in Java?
Local variables in Java do not have a default value. They must be initialized before they are used. Unlike instance variables, which are
given default values by Java (e.g., 0 for integers, null for objects), local variables must be explicitly assigned a value before usage.
Q 31. What is the difference between `HashMap` and `ConcurrentHashMap` in Java?
`HashMap` and `ConcurrentHashMap` are both part of the Java Collections Framework and are used to store key-value pairs.
However, they have signicant differences, especially in terms of thread safety and performance in a multithreaded environment.
Try it Yourself >>
Try it Yourself >>
Feature HashMap ConcurrentHashMap
Not thread-safe. Must be synchronized externally forThread-safe. Uses internal locking mechanisms for
Thread Safety
multithreaded access. thread safety.
Null
Values
Keys and
Allows one null key and multiple null values. Does not allow null keys or null values.
Optimized for multithreaded environments with
minimal contention.
Uses a segmented locking mechanism for better
concurrency.
Java 1.5 (Concurrent package)
Performance Faster in single-threaded environments.
Locking
Mechanism
Introduced In
Entire map must be synchronized externally.
Java 1.2
Output
Key Differences between ̀`join()` and ̀`wait()`
import java.util.*;
import java.util.concurrent.*;
public class MapComparisonExample {
public static void main(String[] args) {
// HashMap example (Not thread-safe)
Map hashMap = new HashMap<>();
hashMap.put("Key1", "Value1");
hashMap.put("Key2", "Value2");
System.out.println("HashMap: " + hashMap);
HashMap: {Key1=Value1, Key2=Value2}
ConcurrentHashMap: {Key1=Value1, Key2=Value2}
ConcurrentHashMap does not allow null keys or values.
}
// ConcurrentHashMap example (Thread-safe) Map
concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("Key1", "Value1");
concurrentHashMap.put("Key2", "Value2");
System.out.println("ConcurrentHashMap: " + concurrentHashMap);
// Attempting null key and value
try {
hashMap.put(null, "NullValue");
concurrentHashMap.put(null, "NullValue");
} catch (Exception e) {
System.out.println("ConcurrentHashMap does not allow null keys or values.");
}
}
Q 32. What is the difference between `join()` and `wait()` in Java?
Both `join()` and `wait()` are used for thread coordination in Java, but they serve different purposes and operate differently. While
`join()` is specically designed to make one thread wait for another to complete, `wait()` is used for inter-thread communication
and can be customized for broader use cases.
Feature
Purpose
Class
Lock Behavior
Synchronized
Block
Use Case
Try it Yourself >>
`join()` `wait()`
Used for inter-thread communication, making the current
thread wait until it is notied.
Belongs to the ̀`Object` class.
Used to wait for the completion of another thread.
Belongs to the ̀`Thread` class.
Does not release any locks while waiting forReleases the lock on the object it is called on and waits to be
another thread to nish. notied.
No need to call inside a synchronized block. Must be called within a synchronized block or method.
Used to ensure one thread nishes executionUsed to implement producer-consumer or similar inter-thread
before another starts. communication patterns.
Example: ̀`join()` vs ̀`wait()`
t1.start();
Thread.sleep(100); // Ensure t1 calls wait first
t2.start();
}
// Demonstrating join()
WorkerThread t3 = new WorkerThread();
t3.start();
System.out.println("Main thread waiting for t3 to finish...");
t3.join();
System.out.println("Main thread resumes after t3 completes.");
}
// Demonstrating wait() and notify()
Thread t1 = new Thread(() -> resource.waitExample(), "Thread-1");
Thread t2 = new Thread(() -> resource.notifyExample(), "Thread-2");
class SharedResource {
}
class WorkerThread extends Thread {
synchronized void waitExample() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting...");
wait();
System.out.println(Thread.currentThread().getName() + " resumed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
s y n c h r o n i z e d v o i d n o t i f y E x a m p l e ( ) {
System.out.println(Thread.currentThread().getName() + " is notifying...");
notify();
}
}
public class JoinVsWaitExample {
public void run() {
System.out.println(Thread.currentThread().getName() + " started.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e (
}
public static void main(String[] args) throws InterruptedException {
SharedResource resource = new SharedResource();
Try it Yourself >>
Output
Output
Example
Name in Dog class: Dog
Name in Animal class: Animal
Animal class method
Thread-1 is waiting...
Thread-2 is notifying...
Thread-1 resumed.
Main thread waiting for t3 to finish...
Thread-3 started.
Thread-3 finished.
Main thread resumes after t3 completes.
// Java Example: Using the super Keyword
class Animal {
String name = "Animal";
} c l a s s D o g
e x t e n d s
A n i m a l {
void display() {
System.out.println("Animal class method");
}
String name = "Dog";
}
void show() {
System.out.println("Name in Dog class: " + name);
System.out.println("Name in Animal class: " + super.name); // Accessing superclass variable
super.display(); // Calling superclass method
}
p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s ) {
Dog dog = new Dog();
dog.show();
}
Q 34. What is a Singleton class in Java?
A Singleton class in Java is a class that allows only one instance of itself to be created. It is used to restrict the instantiation of a
class to a single object. This pattern is useful when you need to control access to resources, such as a database connection or a
Q 33. What is the purpose of the super keyword in Java?
The super keyword in Java refers to the superclass (parent class) of the current object. It is used to access members (variables,
methods, and constructors) of the parent class. It is primarily used in inheritance to refer to the superclass's methods and
variables and to call the constructor of the superclass.
Try it Yourself >>
Try it Yourself >>
logging mechanism, and ensure there is only one instance of that resource.
A palindrome is a word, phrase, or number that reads the same forward and backward. This question tests the candidate's
understanding of string manipulation and control structures.
Output
Example
Example: Checking Palindrome
This is a Singleton class.
// Java Example: Singleton Class
class Singleton {
private static Singleton instance;
}
private Singleton() {
// Private constructor to prevent instantiation
}
p u b l i c s t a t i c S i n g l e t o n g e t I n s t a n c e ( ) {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void displayMessage() {
System.out.println("This is a Singleton class.");
}
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.displayMessage();
}
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = true;
// Convert string to lowercase to ignore case sensitivity
str = str.toLowerCase();
// Check if string is equal to its reverse
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
isPalindrome = false; // If characters don't match, it's not a palindrome
break;
}
}
Q 35. Write a Java program to check if a given string is a palindrome or not.
Output
Example: Demonstrating Polymorphism with Method Overriding
madam is a palindrome.
// Polymorphism in action animal1.sound(); //
Calls Dog's sound method animal2.sound(); //
Calls Cat's sound method
class Animal {
}
class Dog extends Animal {
// Method in the superclass
void sound() {
System.out.println("Animals make sounds.");
}
} c l a s s C a t
e x t e n d s
A n i m a l {
// Overriding the method in the subclass
@Override
void sound() {
System.out.println("Dog barks.");
}
} p u b l i c c l a s s
P o l y m o r p h i s m E x
a m p l e {
// Overriding the method in the subclass
@Override
void sound() {
System.out.println("Cat meows.");
}
public static void main(String[] args) {
// Parent class reference pointing to child objects
Animal animal1 = new Dog(); Animal animal2 = new
Cat();
}
if (isPalindrome) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
Q 36. Design a Java program to demonstrate polymorphism using method overriding.
Polymorphism in object-oriented programming allows a single interface to represent different underlying forms (data types). In Java,
polymorphism is achieved through method overriding, where a subclass provides a specic implementation of a method that is
already dened in its superclass.
Try it Yourself >>
Output
Example: Demonstrating Inheritance and Encapsulation
}
}
Dog barks.
Cat
meows.
class Employee {
// Encapsulation: private fields
private String name;
private int age;
private double salary;
// Constructor
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
/ / G e t t e r a n d S e t t e r m e t h o d s t o a c c e s s p r i v a t e f i e l d s
p u b l i c S t r i n g g e t N a m e ( ) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary);
}
Q 37. Design a Java program to demonstrate inheritance and encapsulation.
Inheritance in Java allows a class to inherit properties and behaviors from another class, promoting code reuse. Encapsulation in
Java is the mechanism of wrapping data (elds) and methods into a single unit and restricting direct access to some components
using access modiers.
Try it Yourself >>
Output
Name: Alice, Age: 30, Salary: 50000.0
Name: Bob, Age: 40, Salary: 80000.0
Department: IT
Updated Salary of Manager: 85000.0
}
// Subclass inheriting from the Employee superclass
class Manager extends Employee {
}
public class InheritanceEncapsulationExample {
private String department;
// Constructor
public Manager(String name, int age, double salary, String department) {
super(name, age, salary); // Call superclass constructor
this.department = department;
}
/ / M e t h o d t o d i s p l a y m a n a g e r - s p e c i f i c d e t a i l s
p u b l i c v o i d d i s p l a y D e t a i l s ( ) {
super.displayDetails(); // Call superclass method
System.out.println("Department: " + department);
}
}
public static void main(String[] args) {
// Creating Employee object
Employee employee = new Employee("Alice", 30, 50000);
employee.displayDetails();
// Creating Manager object
Manager manager = new Manager("Bob", 40, 80000, "IT");
manager.displayDetails();
// Using Encapsulation: Updating details
manager.setSalary(85000);
System.out.println("Updated Salary of Manager: " + manager.getSalary());
}
Q 38. What is the difference between nal, nally, and nalize in Java?
nal, nally, and nalize are three distinct concepts in Java, and they serve different purposes:
nalize
Keyword
Method
nal
nally
/
Try it Yourself >>
Description
Used to declare constants, prevent method overriding, and prevent inheritance of classes.
Used to dene a block of code that will always execute after a try-catch block, regardless of whether an
exception was thrown or not.
A method called by the garbage collector just before an object is destroyed. It is used for cleanup operations
before an object is discarded.
Output
Example
Example
// Java Example: transient keyword
import java.io.*;
class Person implements Serializable {
String name;
transient String password; // transient field
public Person(String name, String password) {
this.name = name;
this.password = password;
}
Exception caught
Finally block executed
Finalize method called before object is garbage collected
// Java Example: final, finally, finalize
public class FinalExample {
}
final int MAX_VALUE = 100; // final variable
void testFinally() {
try {
int result = 10 / 0; // Will throw exception
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
System.out.println("Finally block executed");
}
}
p r o t e c t e d v o i d f i n a l i z e ( ) {
System.out.println("Finalize method called before object is garbage collected");
}
public static void main(String[] args) {
FinalExample example = new FinalExample();
example.testFinally();
// Explicitly calling finalize for demonstration
example = null;
System.gc(); // Requesting garbage collection
}
Q 39. What is the purpose of the transient keyword in Java?
The transient keyword in Java is used to indicate that a particular eld should not be serialized. When an object is serialized, its non-
transient elds are saved to the stream, while transient elds are ignored. This is useful when certain elds should not be part of the
serialized data, such as sensitive information (e.g., passwords) or elds that are derived at runtime.
Try it Yourself >>
Output
Example: Sorting a List of Employees by Salary
Name: John
Password: null
import java.util.*;
class Employee {
private String name;
private int age;
private double salary;
// Constructor
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
/ / G e t t e r s
// Deserialization FileInputStream fileIn = new
FileInputStream("person.ser"); ObjectInputStream in = new
ObjectInputStream(fileIn); Person deserializedPerson = (Person)
in.readObject(); in.close();
fileIn.close();
// Serialization
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("John", "secret");
}
System.out.println("Name: " + deserializedPerson.name);
System.out.println("Password: " + deserializedPerson.password); // null, because password is transient
}
Q 40. Write a Java program to sort a list of objects using `Comparator`.
The `Comparator` interface in Java is used to dene custom sorting logic for objects. It allows sorting objects based on different
elds without modifying their class denition.
Try it Yourself >>
Output
Example
// Java Example: Static Block
class StaticExample {
static int x;
Employees sorted by salary:
Employee{name='Bob', age=25, salary=60000.0}
Employee{name='Alice', age=30, salary=70000.0}
Employee{name='Charlie', age=35, salary=90000.0}
}
public class SortEmployees {
public String getName() {
return name;
}
p u b l i c i n t g e t A g e ( ) {
return age;
}
public double getSalary() {
return salary;
}
/ / T o d i s p l a y E m p l o y e e d e t a i l s
@ O v e r r i d e
p u b l i c S t r i n g t o S t r i n g ( ) {
return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}";
}
}
public static void main(String[] args) {
List employees = new ArrayList<>();
employees.add(new Employee("Alice", 30, 70000));
employees.add(new Employee("Bob", 25, 60000));
employees.add(new Employee("Charlie", 35, 90000));
// Sorting employees by salary using Comparator
employees.sort(Comparator.comparingDouble(Employee::getSalary));
// Displaying sorted employees
System.out.println("Employees sorted by salary:");
for (Employee e : employees) {
System.out.println(e);
}
}
Q 41. What is a static block in Java?
A static block in Java is a block of code that gets executed when the class is loaded into memory, before any object of the class is
created. It is used to initialize static variables or to perform any setup that should happen only once when the class is loaded. Static
blocks are executed in the order in which they appear in the class.
Try it Yourself >>
Output
Example
Static block executed
Value of x: 10
// Java Example: HashMap vs TreeMap
import java.util.*;
// TreeMap Example
Map treeMap = new TreeMap<>();
treeMap.put("Apple", "Fruit");
}
public static void main(String[] args) {
System.out.println("Value of x: " + x);
}
public class MapExample {
public static void main(String[] args) {
// HashMap Example
Map hashMap = new HashMap<>();
hashMap.put("Apple", "Fruit");
hashMap.put("Carrot", "Vegetable");
System.out.println("HashMap: " + hashMap);
// Static block to initialize static variables
static {
x = 10;
System.out.println("Static block executed");
}
Q 42. What is the difference between HashMap and TreeMap in Java?
Both HashMap and TreeMap are implementations of the Map interface, but they differ in the way they store and access elements:
Underlying
Structure
Performance
Null Keys/Values
Aspect
Order of Elements
Try it Yourself >>
HashMap
No order guaranteed (elements are
unordered).
Allows one null key and any number of
null values.
TreeMap
Sorted according to the natural order of keys or a custom
comparator.
Does not allow null keys (throws NullPointerException) but
allows null values.
Faster for basic operations (O(1) for get
and put).
Hash table (uses hash function for
indexing).
Slower for basic operations (O(log n) for get and put due to
sorting).
Red-Black tree (balanced binary tree).
Data
Output
Output
Example
StringBuffer: Hello World
StringBuilder: Hello World
HashMap: {Apple=Fruit, Carrot=Vegetable}
TreeMap: {Apple=Fruit, Carrot=Vegetable}
}
treeMap.put("Carrot", "Vegetable");
System.out.println("TreeMap: " + treeMap);
}
// Java Example: StringBuffer vs StringBuilder
public class StringExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello");
stringBuffer.append(" World");
System.out.println("StringBuffer: " + stringBuffer);
}
StringBuilder stringBuilder = new StringBuilder("Hello");
stringBuilder.append(" World");
System.out.println("StringBuilder: " + stringBuilder);
}
Q 44. What is the difference between process and thread in Java?
In Java, both processes and threads are used for concurrent execution, but they differ in the following ways:
Q 43. What is the difference between StringBuffer and StringBuilder in Java?
Both StringBuffer and StringBuilder are used for creating mutable strings, but there are key differences between them:
Aspect
Aspect
Thread Safety
Performance
Use Case
Try it Yourself >>
Try it Yourself >>
Process
StringBuffer
Thread-safe (synchronized).
Slower due to synchronization overhead.
Used when thread safety is required.
Thread
StringBuilder
Not thread-safe (not synchronized).
Faster as it does not have synchronization overhead.
Used when thread safety is not required and performance is a priority.
Try it Yourself >>
Denition A process is an independent program in execution. A thread is a small unit of a process, representing a
single sequence of execution.
Threads share the memory space of their parent
process.
Lower overhead as threads share resources within
the same process.
Memory Each process has its own memory space.
Overhead Higher overhead due to independent memory allocation
and resource management.
Communication Inter-process communication (IPC) is required for
communication between processes.
Threads can communicate directly as they share
memory within the same process.
The volatile keyword in Java is used to indicate that a variable's value may be changed by different threads. It ensures that any update
to the variable is visible to all threads immediately without caching it in a thread's local memory. This is crucial for proper
synchronization between threads and ensures the latest value is always visible across different threads.
Output
Example
Example
Thread is running...
// Java Example: Volatile Keyword
class SharedResource {
private volatile boolean flag = false;
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
public void toggleFlag() {
flag = !flag;
}
p u b l i c v o i d c h e c k F l a g ( ) {
if (flag) {
System.out.println("Flag is true");
}
}
public static void main(String[] args) {
// Java Example: Thread Example
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
Q 45. What is the use of the volatile keyword in Java?
Output
Output
Example
Flag is true
// Java Example: Checked vs Unchecked Exception
import java.io.*;
}
SharedResource resource = new SharedResource();
resource.toggleFlag();
resource.checkFlag();
}
class ExceptionExample {
}
public static void main(String[] args) {
try {
// Checked exception: IOException
FileReader file = new FileReader("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Caught Checked Exception: " + e);
}
// Unchecked exception: NullPointerException
String str = null;
try {
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Caught Unchecked Exception: " + e);
}
}
Q 46. What is the difference between checked and unchecked exceptions in Java?
In Java, exceptions are classied into two categories: checked exceptions and unchecked exceptions.
Try it Yourself >>
Try it Yourself >>
Aspect
Denition
Checked Exception
Checked exceptions are exceptions that are checked
at compile-time.
IOException, SQLException.
Must be explicitly caught or declared in the method
signature.
Unchecked Exception
Unchecked exceptions are exceptions that are not checked at
compile-time.
NullPointerException, ArrayIndexOutOfBoundsException.
Optional to handle or declare in the method signature.
Example
Handling
Factorial of 5 is: 120
public class LargestElement {
public static void main(String[] args) {
int[] numbers = {10, 25, 4, 99, 18, 54};
int largest = numbers[0]; // Assume first element is the largest
// Loop through the array to find the largest element
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update largest element
}
}
System.out.println("Largest element in the array is: " + largest);
public class FactorialRecursion {
}
// Recursive method to find factorial
public static int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
}
r e t u r n n * f a c t o r i a l ( n - 1 ) ; / / R e c u r s i v e c a l l
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
Caught Checked Exception: java.io.FileNotFoundException: nonexistentfile.txt (No such file or directory)
Caught Unchecked Exception: java.lang.NullPointerException
Q 47. Write a Java program to nd the factorial of a number using recursion.
Recursion is a fundamental concept in programming where a function calls itself to solve smaller instances of the problem. This
question checks your understanding of recursion.
Q 48. Write a Java program to nd the largest element in an array without using built-in
methods.
This question tests your ability to manipulate arrays and implement basic logic without relying on Java's built-in methods like
`Arrays.sort()` or ̀`Collections.max()`.
Try it Yourself >>
Output
Example: Finding Factorial Using Recursion
Example: Finding the Largest Element in an Array
Output
Output
Example
}
}
ArrayList: [Apple, Banana]
Vector: [Apple, Banana]
Largest element in the array is: 99
// Java Example: ArrayList vs Vector
import java.util.*;
}
// Vector Example
List vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
System.out.println("Vector: " + vector);
}
public class ListExample {
public static void main(String[] args) {
// ArrayList Example
List arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
System.out.println("ArrayList: " + arrayList);
Q 50. What are the different access modiers in Java?
Q 49. What is the difference between ArrayList and Vector in Java?
ArrayList and Vector are both resizable array implementations of the List interface, but they have several differences:
Aspect
Thread Safety
Growth Policy
Performance
Use Case
Try it Yourself >>
Try it Yourself >>
ArrayList
Not thread-safe.
Resizes by 50% when full.
Faster as it does not have synchronization overhead.
Preferred when thread safety is not a concern.
Vector Thread-safe (synchronized).
Resizes by doubling its size when full.
Slower due to synchronization overhead.
Preferred when thread safety is required.
Try it Yourself >>
Modier
public
private
protected
default (No Modier)
Description
Accessible from any other class.
Accessible only within the same class.
Accessible within the same package and by subclasses.
Accessible only within the same package.
In Java, access modiers determine the visibility or accessibility of classes, methods, and variables. There are four main access
modiers:
In conclusion, preparing for a Java interview with 3 years of experience is essential for showcasing your understanding of key
concepts. By reviewing the commonly asked Java interview questions and practicing with clear answers and code examples,
you can strengthen your preparation and improve your condence. This article serves as a valuable resource to help you
succeed in your Java interview and advance in your career. To enhance your skills further, consider enrolling in our Free Java
Certication Course, which provides in-depth learning and certication to boost your career prospects.
Dear learners, ScholarHat provides you with Free Tech Trendy Masterclasses to help you learn and immerse yourself in the latest
trending technologies.
Output
Example
Public Variable: 10
Private Variable: 20
Protected Variable: 30
}
// Method to display the values of the variables
void display() {
System.out.println("Public Variable: " + publicVar);
System.out.println("Private Variable: " + privateVar);
System.out.println("Protected Variable: " + protectedVar);
}
class AccessModifiersExample {
public static void main(String[] args) {
AccessModifiersExample example = new AccessModifiersExample();
example.display(); // Calls the display method to print the variables
}
public int publicVar = 10;
private int privateVar = 20;
// Can be accessed anywhere
// Can only be accessed within this class
protected int protectedVar = 30; // Can be accessed within this class and subclasses
Conclusion

Java Interview Questions PDF By ScholarHat

  • 1.
    Java Interview Questionsfor 3 years Experience Java Interview Questions for 3 Years of Experience Preparing for a Java interview Questions for 3 Years of Experience can be challenging, especially with all the different topics that could come up. If you have about three years of experience with Java, it’s important to be familiar with both basic and advanced concepts. This article offers a helpful list of Java interview questions for Freshers, covering everything you need to know. By practicing these questions, you’ll feel more confident and ready to show your skills in the interview. Top 50 Java Interview Questions For 3 Years Experienced Candidates Q 1. What are the main features of Java? Java is a high-level, object-oriented, and platform-independent programming language. Its key features of Java include platform independence, object orientation, robust memory management, exception handling, multithreading, and security features. In this Interview tutorial, let's learn the top 50 Java interview questions for a 3 years' experience candidate. To further strengthen your Java knowledge and enhance your interview preparation, consider enrolling in our Java Online Course Free With Certificate, which offers comprehensive learning and certification to boost your career prospects. Example // Java Example: Platform Independence public class HelloWorld { } public static void main(String[] args) { System.out.println("Hello, Java!"); }
  • 2.
    Output Output Example Hello, Java! Car brand:Tesla, Speed: 200 km/h // Java Example: Creating an Object class Car { String brand; int speed; } p u b l i c c l a s s O b j e c t E x a m p l e { void display() { System.out.println("Car brand: " + brand + ", Speed: " + speed + " km/h"); } } public static void main(String[] args) { Car myCar = new Car(); myCar.brand = "Tesla"; myCar.speed = 200; myCar.display(); } Q 3. What is an object in Java? An object in Java is an instance of a class. It represents real-world entities with states (variables) and behaviors (methods). Objects are the basic units that help organize and model real-world situations in a Java application. Q 2. What is the difference between JDK, JRE, and JVM? Q 4. What is the difference between abstraction and encapsulation in Java? Users Aspect Purpose Components Try it Yourself >> Try it Yourself >> JDK (Java Development Kit) JRE (Java Runtime Environment) Provides the runtime environment for Java programs. JVM (Java Virtual Machine) Executes Java bytecode. Provides development. Includes JRE, compiler, debugger, and development tools. Used by developers to write Java programs. tools for Java Includes required for execution. Used by end-users to run Java programs. JVM and libraries Part of the JRE, performs execution and memory management. Used internally by JRE to execute code.
  • 3.
    Try it Yourself>> Aspect Denition Abstraction Hides implementation details and shows only the functionality. Encapsulation Hides the internal state of an object and protects it from unauthorized access. Focus Implementation Focuses on "what" the object does. Achieved using abstract classes and interfaces. Focuses on "how" the object's data is protected. Achieved by declaring variables private and providing getters and setters. A constructor in Java is a special method that is used to initialize objects. It is called automatically when an object of a class is created. It does not have a return type and has the same name as the class. Output Example Example Woof! Woof! // Java Example: Abstraction and Encapsulation abstract class Animal { } class Dog extends Animal { abstract void sound(); } public class AbstractionExample { void sound() { System.out.println("Woof! Woof!"); } } public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); } // Java Example: Constructor class Car { } p u b l i c c l a s s C o n s t r u c t o r E x a m p l e { String brand; // Constructor Car(String brand) { this.brand = brand; } v o i d d i s p l a y ( ) { System.out.println("Car brand: " + brand); } Q 5. What is a constructor in Java?
  • 4.
    Output Output Example Example Car brand: Tesla Sumof integers: 15 Sum of doubles: 16.0 } public static void main(String[] args) { Car myCar = new Car("Tesla"); myCar.display(); } // Java Example: Method Overloading class Calculator { } p u b l i c c l a s s O v e r l o a d i n g E x a m p l e { int add(int a, int b) { return a + b; } d o u b l e a d d ( d o u b l e a , d o u b l e b ) { return a + b; } } public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println("Sum of integers: " + calc.add(5, 10)); System.out.println("Sum of doubles: " + calc.add(5.5, 10.5)); } Q 7. What is method overriding in Java? Method overriding in Java occurs when a subclass provides a specic implementation for a method already dened in its superclass. The overridden method in the subclass must have the same signature as the method in the superclass. Q 6. What is method overloading in Java? Method overloading in Java refers to dening multiple methods in a class with the same name but different parameters (either in number or type). Overloading increases the readability of the program. Try it Yourself >> Try it Yourself >>
  • 5.
    Output Example Dog barks // JavaExample: Method Overriding class Animal { } class Dog extends Animal { void sound() { System.out.println("Animal makes a sound"); } } p u b l i c c l a s s O v e r r i d i n g E x a m p l e { @Override void sound() { System.out.println("Dog barks"); } } public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); } // Java Example: == vs equals() class Person { } public class ComparisonExample { String name; Person(String name) { this.name = name; } public static void main(String[] args) { Person p1 = new Person("John"); Person p2 = new Person("John"); System.out.println("Using ==: " + (p1 == p2)); // false Q 8. What is the difference between == and equals() in Java? The "==" operator compares the memory addresses of two objects, i.e., whether the two references point to the same memory location. The equals() method compares the actual content of the objects to check if they are logically equivalent. Aspect Comparison Type Default Behavior Try it Yourself >> == Operator Compares references (memory location). Used for primitives and references. Compares memory locations by default. equals() Method Compares content of objects. Used only for objects. Compares object data; must be overridden in custom classes.
  • 6.
    Output Output Example Animal makes asound Dog barks Using ==: false Using equals(): true // Java Example: super keyword class Animal { } class Dog extends Animal { void sound() { System.out.println("Animal makes a sound"); } } p u b l i c c l a s s S u p e r E x a m p l e { void sound() { super.sound(); // Calling the parent class method System.out.println("Dog barks"); } } public static void main(String[] args) { Dog myDog = new Dog(); myDog.sound(); } } System.out.println("Using equals(): " + p1.name.equals(p2.name)); // true } Q 9. What is the use of the super keyword in Java? The super keyword in Java refers to the immediate parent class object. It is commonly used to access parent class methods and constructors from the subclass. Q 10. What is the difference between ArrayList and LinkedList in Java? ArrayList and LinkedList both implement the List interface, but their internal structure and performance characteristics differ: Aspect Internal Structure Try it Yourself >> Try it Yourself >> ArrayList Backed by a dynamic array. LinkedList Backed by a doubly linked list.
  • 7.
    Thread Safety Thread Safety Aspect Immutability Memory Consumption Access Speed Insertion/Deletion Try itYourself >> String Immutable (cannot be changed after creation). Not thread-safe. StringBuffer Mutable (can be modied). StringBuilder Mutable (can be modied). Thread-safe methods). Slower due to synchronization overhead. (synchronized Not thread-safe. Slower due to immutability. Faster than StringBuffer due synchronization. to no Faster access (O(1)) for indexed operations. Slower insertion and deletion (O(n)) in the middle. Uses less memory compared to LinkedList. Slower access (O(n)) due to traversal. Faster insertion/deletion (O(1)) at both ends. Consumes more memory due to extra references in each node. String, StringBuffer, and StringBuilder are used to represent strings in Java. The key differences lie in their mutability and thread safety: Output Example Example ArrayList: [10, 20] LinkedList: [30, 40] // Java Example: ArrayList vs LinkedList import java.util.*; public class ListExample { } public static void main(String[] args) { List arrayList = new ArrayList<>(); List linkedList = new LinkedList<>(); arrayList.add(10); arrayList.add(20); linkedList.add(30); linkedList.add(40); System.out.println("ArrayList: " + arrayList); System.out.println("LinkedList: " + linkedList); } // Java Example: String vs StringBuffer vs StringBuilder public class StringExample { public static void main(String[] args) { String str1 = "Hello"; Q 11. What is the difference between String, StringBuffer, and StringBuilder?
  • 8.
    Output Output Example Woof String: Hello World StringBuffer:Hello World StringBuilder: Hello World // Java Example: Interface interface Animal { } class Dog implements Animal { void sound(); } public class InterfaceExample { public void sound() { System.out.println("Woof"); } } public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); } str1 = str1 + " World"; StringBuffer buffer = new StringBuffer("Hello"); buffer.append(" World"); StringBuilder builder = new StringBuilder("Hello"); builder.append(" World"); System.out.println("String: " + str1); System.out.println("StringBuffer: " + buffer); System.out.println("StringBuilder: " + builder); } } Q 12. What is an interface in Java? An interface in Java is a reference type similar to a class, but it can only contain constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance elds or constructors. It is used to achieve abstraction and multiple inheritance. Try it Yourself >> Try it Yourself >>
  • 9.
    Q 13. Whatis the difference between Method Overloading and Method Overriding? Method Overloading and Method Overriding are both used to achieve polymorphism, but they differ in how they are implemented and used: Aspect Denition Compile-Time Run-Time Inheritance Return Type Access Modier Does not require inheritance. It can have a different return type. It can have different access modiers. Requires inheritance or interface implementation. It must have the same return type. It must have the same or a more accessible access modier. Method Overloading Dening multiple methods with the same name but different parameter lists. Occurs at compile-time (Static Polymorphism). Method Overriding Providing a new implementation for a method already dened in the parent class. Occurs at run-time (Dynamic Polymorphism). vs Let's learn the difference between Method Overloading and Method Overiding. Example // Java Example: Method Overloading vs Method Overriding class Animal { } c l a s s D o g e x t e n d s A n i m a l { void sound() { System.out.println("Animal makes a sound"); } } p u b l i c c l a s s O v e r l o a d O v e r r i d e E x a m p l e { // Overriding method void sound() { System.out.println("Dog barks"); } / / O v e r l o a d i n g m e t h o d v o i d s o u n d ( S t r i n g s o u n d T y p e ) { System.out.println("Dog " + soundType); } public static void main(String[] args) { Animal animal = new Animal(); animal.sound(); // Calls parent method Dog dog = new Dog(); dog.sound(); // Calls overridden method
  • 10.
    Output Output Example Example Name: John Animal makesa sound Dog barks Dog whines } dog.sound("whines"); // Calls overloaded method } // Java Example: this keyword class Person { } p u b l i c c l a s s T h i s K e y w o r d E x a m p l e { String name; Person(String name) { this.name = name; // 'this' refers to the current object's instance variable } v o i d d i s p l a y ( ) { System.out.println("Name: " + this.name); // 'this' used to refer to current object's field } } public static void main(String[] args) { Person person = new Person("John"); person.display(); } Q 15. What are Java Collections? Java Collections framework provides a set of classes and interfaces that implement commonly used collection data structures. The Collections framework includes the following interfaces: List, Set, Queue, and Map, each with various implementations like ArrayList, HashSet, LinkedList, PriorityQueue, and HashMap. Q 14. What is the use of 'this' keyword in Java? The "this" keyword in Java is used to refer to the current object of the class. It helps distinguish between instance variables and local variables when they have the same name, and it is also used to call one constructor from another constructor in the same class. Try it Yourself >> Try it Yourself >>
  • 11.
    Output Example List: [Apple, Banana] Set:[Apple, Banana] Map: {1=Apple, 2=Banana} // Java Example: Constructor class Car { String model; // Constructor Car(String model) { this.model = model; } // Set implementation Set set = new HashSet<>(); set.add("Apple"); set.add("Banana"); // Map implementation Map map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); } System.out.println("List: " + list); System.out.println("Set: " + set); System.out.println("Map: " + map); } // Java Example: Collections Framework import java.util.*; public class CollectionsExample { public static void main(String[] args) { // List implementation List list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); void display() { System.out.println("Car model: " + this.model); } Q 16. What is a constructor in Java? A constructor in Java is a special method used to initialize objects in Java. It is called when an object of a class is created, and it is used to set the initial values for the object's instance variables. Try it Yourself >>
  • 12.
    Output Example Car model: Tesla } publicclass ConstructorExample { } public static void main(String[] args) { Car car = new Car("Tesla"); car.display(); } // Java Example: final, finally, finalize class MyClass { } public class FinalExample { final int x = 10; void display() { System.out.println("Value of x: " + x); } / / f i n a l i z e m e t h o d protected void finalize() { System.out.println("Object is being garbage collected"); } } public static void main(String[] args) { MyClass obj = new MyClass(); obj.display(); obj = null; // eligible for garbage collection System.gc(); // Requesting garbage collection } Q 17. What is the difference between nal, nally, and nalize in Java? nal, nally, and nalize are different concepts in Java: Try it Yourself >> Execution Executed at compile-time. Aspect Denition nal Used to dene constants, prevent prevent method inheritance. overriding, or Usage It methods, or classes. can be applied to variables, nally Used to dene a block of code that will always execute, regardless of exception handling. Used in exception handling blocks (try- catch-nally). nalize Used to perform cleanup before an object is garbage collected. Called by the garbage collector when the object is ready for a cleanup. Called by garbage collector, not guaranteed to be called. Executed at runtime, always after the try- catch block.
  • 13.
    Output Output Example Hello World Hello World Valueof x: 10 Object is being garbage collected } StringBuffer sf = new StringBuffer("Hello"); sf.append(" World"); System.out.println(sf); } // Java Example: StringBuilder vs StringBuffer public class StringBuilderBufferExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb); Q 19. What is the purpose of the static keyword in Java? The static keyword in Java is used for memory management. It is applied to variables, methods, blocks, and nested classes. Static members belong to the class rather than instances, meaning they can be accessed without creating an object of the class. Static variables are shared among all instances of a class, and static methods can be invoked without creating an object. Q 18. What is the difference between StringBuilder and StringBuffer in Java? StringBuilder and StringBuffer are both used for creating mutable strings, but the main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not. Therefore, StringBuffer is slower than StringBuilder. Aspect Thread Safety Performance Use Case Methods Try it Yourself >> Try it Yourself >> StringBuilder Not thread-safe (faster). Faster because it is not synchronized. Used when thread safety is not required. Uses methods like append(), insert(), delete(), etc. StringBuffer Thread-safe (slower). Slower due to synchronization. Used when thread safety is required. Same methods as StringBuilder but synchronized.
  • 14.
    Output Example Example: Creating andUsing a Custom Annotation Count: 2 // Java Example: Custom Annotation import java.lang.annotation.*; import java.lang.reflect.*; // Step 1: Define the custom annotation @Retention(RetentionPolicy.RUNTIME) // Retain at runtime @Target(ElementType.METHOD) @interface MyAnnotation { // Apply only to methods } // Step 2: Annotate methods with the custom annotation class MyClass { String value() default "Default Message"; @MyAnnotation(value = "Hello, World!") public void myMethod() { System.out.println("Executing myMethod()"); } @MyAnnotation // Java Example: Static Keyword class Counter { } p u b l i c c l a s s S t a t i c K e y w o r d E x a m p l e { static int count = 0; Counter() { count++; } static void displayCount() { System.out.println("Count: " + count); } } public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter.displayCount(); // Accessing static method without object } Q 20. What are Java annotations, and how are custom annotations created? Try it Yourself >> Annotations in Java are metadata that provide additional information about the code. They do not affect the code execution directly but are used by the compiler or during runtime to perform certain tasks such as code analysis or processing. Common built-in annotations include ̀`@Override`, ̀`@Deprecated`, and ̀`@SuppressWarnings`. Custom annotations can also be created to define specific metadata for your application. They are defined using the `@interface` keyword and can include elements (like methods) to specify additional values.
  • 15.
    Output Example Method: myMethod Annotation Value:Hello, World! Executing myMethod() Method: anotherMethod Annotation Value: Default Message Executing anotherMethod() // Java Example: Observer Design Pattern import java.util.*; interface Observer { } class ConcreteObserver implements Observer { void update(String message); private String name; public ConcreteObserver(String name) { this.name = name; } // Step 3: Access the annotation using reflection public class AnnotationExample { public void anotherMethod() { System.out.println("Executing anotherMethod()"); } } public static void main(String[] args) throws Exception { MyClass obj = new MyClass(); Method[] methods = obj.getClass().getDeclaredMethods(); for (Method method : methods) { // Check if MyAnnotation is present if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); System.out.println("Method: " + method.getName()); System.out.println("Annotation Value: " + annotation.value()); method.invoke(obj); // Call the method System.out.println(); } } } Q 21. What is the Observer Design Pattern in Java? The Observer Design Pattern is a behavioral pattern where an object (subject) maintains a list of dependent objects (observers) that are notied of any state changes. This pattern is typically used in scenarios where an object needs to update other objects automatically when its state changes without tight coupling between the objects. Try it Yourself >>
  • 16.
    Output Observer1 received message:State Changed! Observer2 received message: State Changed! } class Subject { } @ O v e r r i d e p u b l i c v o i d u p d a t e ( S t r i n g m e s s a g e ) { System.out.println(name + " received message: " + message); } } p u b l i c c l a s s O b s e r v e r P a t t e r n E x a m p l e { private List observers = new ArrayList<>(); public void addObserver(Observer observer) { observers.add(observer); } p u b l i c v o i d r e m o v e O b s e r v e r ( O b s e r v e r o b s e r v e r ) { observers.remove(observer); } p u b l i c v o i d n o t i f y O b s e r v e r s ( S t r i n g m e s s a g e ) { for (Observer observer : observers) { observer.update(message); } } } public static void main(String[] args) { // Create subject and observers Subject subject = new Subject(); Observer observer1 = new ConcreteObserver("Observer1"); Observer observer2 = new ConcreteObserver("Observer2"); // Register observers subject.addObserver(observer1); subject.addObserver(observer2); // Notify all observers subject.notifyObservers("State Changed!"); } Q 22. What is the difference between `wait()` and `sleep()` methods in Java? The `wait()` and `sleep()` methods are both used to pause the execution of a thread, but they have significant differences in terms of their behavior and usage: Try it Yourself >> wait(): The `wait()` method is used in multithreading and is called on an object’s monitor (lock). It makes the current thread release the lock and enter the waiting state until another thread sends a notification via ̀`notify()` or ̀`notifyAll()`. This method must be called inside a synchronized block or method. sleep(): The `sleep()` method is a static method of the `Thread` class that makes the current thread sleep for a specified number of milliseconds, without releasing any locks. It simply pauses the thread’s execution for the given time period, and does not require synchronization.
  • 17.
    Output Example Example Thread 13 isgoing to wait. Thread 1 is going to sleep. Thread 1 woke up. Thread 13 resumed. public class ExceptionExample { // Java Example: Checked vs Unchecked Exceptions import java.io.*; // Java Example: wait() vs sleep() class WaitExample extends Thread { } p u b l i c c l a s s S l e e p W a i t E x a m p l e { public void run() { synchronized (this) { try { System.out.println("Thread " + Thread.currentThread().getId() + " is going to wait."); wait(5000); // Thread waits for 5 seconds System.out.println("Thread " + Thread.currentThread().getId() + " resumed."); } catch (InterruptedException e) { System.out.println(e); } } } public static void main(String[] args) throws InterruptedException { // Using wait() method WaitExample t1 = new WaitExample(); t1.start(); // Using sleep() method System.out.println("Thread " + Thread.currentThread().getId() + " is going to sleep."); Thread.sleep(3000); // Main thread sleeps for 3 seconds System.out.println("Thread " + Thread.currentThread().getId() + " woke up."); } } Q 23. What are the different types of exceptions in Java? Exceptions in Java are categorized into two main types: Try it Yourself >> Checked Exceptions: These are exceptions that are checked at compile-time. Examples include FileNotFoundException, SQLException, etc. These exceptions must be handled using a try-catch block or declared using the throws keyword. Unchecked Exceptions: These are exceptions that occur at runtime. Examples include ArithmeticException, NullPointerException, etc. These do not need to be handled explicitly.
  • 18.
    Output Example Checked Exception: Filenot found. Unchecked Exception: Cannot divide by zero. // Java Example: finally Block public class FinallyExample { } public static void main(String[] args) { try { System.out.println("Inside try block"); int result = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Exception caught in catch block"); } finally { System.out.println("Finally block executed"); } } public static void main(String[] args) { try { // Checked Exception: FileNotFoundException File file = new File("nonexistentfile.txt"); FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println("Checked Exception: File not found."); } } // Unchecked Exception: ArithmeticException try { int result = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Unchecked Exception: Cannot divide by zero."); } } Q 24. What is the purpose of the nally block in Java? The nally block in Java is used to execute a block of code after a try-catch block, regardless of whether an exception was thrown or not. It is typically used for closing resources such as le streams or database connections. Try it Yourself >> Try it Yourself >>
  • 19.
    Output Example Inside try block Exceptioncaught in catch block Finally block executed // Java Example: Factory Design Pattern interface Animal { } class Dog implements Animal { void makeSound(); } class Cat implements Animal { public void makeSound() { System.out.println("Woof"); } } / / F a c t o r y C l a s s class AnimalFactory { public void makeSound() { System.out.println("Meow"); } } public class FactoryPatternExample { public static Animal getAnimal(String type) { if (type == null) { return null; } if (type.equalsIgnoreCase("Dog")) { return new Dog(); } else if (type.equalsIgnoreCase("Cat")) { return new Cat(); } return null; } public static void main(String[] args) { // Creating objects using Factory Method Animal dog = AnimalFactory.getAnimal("Dog"); dog.makeSound(); // Output: Woof } Animal cat = AnimalFactory.getAnimal("Cat"); cat.makeSound(); // Output: Meow } Q 25. What is the Factory Design Pattern in Java? The Factory Design Pattern is a creational design pattern used to create objects without specifying the exact class of object that will be created. The Factory method allows the creation of objects based on a particular type or condition, abstracting the instantiation process from the client code.
  • 20.
    Output Output Example Example Wo of Meo w Result of addition:8 // Java Example: transient Keyword import java.io.*; class Employee implements Serializable { int id; String name; transient String password; // transient variable public Employee(int id, String name, String password) { this.id = id; // Java Example: Lambda Expression interface MathOperation { } public class LambdaExample { int operate(int a, int b); } public static void main(String[] args) { MathOperation add = (a, b) -> a + b; System.out.println("Result of addition: " + add.operate(5, 3)); } Q 26. What is a Lambda Expression in Java? A Lambda expression in Java is a short block of code that takes in parameters and returns a value. Lambda expressions are used primarily to dene the behavior of methods in functional programming interfaces. Lambda expressions enable the use of methods as arguments in functional programming. Q 27. What is the use of the transient keyword in Java? The transient keyword in Java is used to mark a variable as not to be serialized. If a eld is marked as transient, its value will not be included in the serialization process, which is particularly useful for sensitive information such as passwords. Try it Yourself >> Try it Yourself >>
  • 21.
    Output Example Employee ID: 101 EmployeeName: John Employee Password: null // Java Example: Singleton Design Pattern class Singleton { private static Singleton instance; // Private constructor prevents instantiation from other classes private Singleton() {} // Static method to get the instance of the class public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } r e t u r n i n s t a n c e ; } public class TransientKeywordExample { this.name = name; this.password = password; } } public static void main(String[] args) throws IOException { Employee emp = new Employee(101, "John", "password123"); // Serialization FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(emp); out.close(); fileOut.close(); // Deserialization FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Employee deserializedEmp = (Employee) in.readObject(); in.close(); fileIn.close(); System.out.println("Employee ID: " + deserializedEmp.id); System.out.println("Employee Name: " + deserializedEmp.name); System.out.println("Employee Password: " + deserializedEmp.password); // will be null } Q 28. What is the Singleton Design Pattern in Java? The Singleton design pattern in Javaensures that a class has only one instance and provides a global point of access to that instance. It is useful when you need to control access to shared resources, such as database connections or conguration settings. Try it Yourself >>
  • 22.
    Output Example Singleton Instance: Singleton@5f150435 SingletonInstance: Singleton@5f150435 // Java Example: HashSet vs TreeSet import java.util.*; public class SetExample { public static void main(String[] args) { // HashSet Example Set hashSet = new HashSet<>(); hashSet.add("Banana"); hashSet.add("Apple"); System.out.println("HashSet: " + hashSet); // TreeSet Example Set treeSet = new TreeSet<>(); treeSet.add("Banana"); treeSet.add("Apple"); System.out.println("TreeSet: " + treeSet); } p u b l i c v o i d d i s p l a y ( ) { System.out.println("Singleton Instance: " + this); public static void main(String[] args) { } Singleton singleton1 = Singleton.getInstance(); singleton1.display(); Singleton singleton2 = Singleton.getInstance(); singleton2.display(); } Q 29. What is the difference between HashSet and TreeSet in Java? HashSet and TreeSet are both part of the Set interface in Java, but they differ in their internal data structure and behavior: Aspect Ordering Null Elements Sor ting Performance Try it Yourself >> Does not guarantee sorting. Automatically sorts the elements. HashSet No ordering, elements are stored in an unordered fashion. Faster for operations like add, remove, and contains (O(1)). TreeSet Maintains a natural ordering or a custom order based on a comparator. Slower due to the need to maintain order (O(log n)). Allows null elements. Does not allow null elements.
  • 23.
    Output Output Example Example: Using HashMapand ConcurrentHashMap Key Differences between ̀`HashMap` and ̀`ConcurrentHashMap` } } HashSet: [Apple, Banana] TreeSet: [Apple, Banana] // Compile-time error: variable number might not have been initialized // Java Example: Default Value of Local Variable public class LocalVariableExample { public static void main(String[] args) { // Local variable (uninitialized) int number; // System.out.println(number); // Uncommenting this will give a compile-time error } } Q 30. What is the default value of a local variable in Java? Local variables in Java do not have a default value. They must be initialized before they are used. Unlike instance variables, which are given default values by Java (e.g., 0 for integers, null for objects), local variables must be explicitly assigned a value before usage. Q 31. What is the difference between `HashMap` and `ConcurrentHashMap` in Java? `HashMap` and `ConcurrentHashMap` are both part of the Java Collections Framework and are used to store key-value pairs. However, they have significant differences, especially in terms of thread safety and performance in a multithreaded environment. Try it Yourself >> Try it Yourself >> Feature HashMap ConcurrentHashMap Not thread-safe. Must be synchronized externally forThread-safe. Uses internal locking mechanisms for Thread Safety multithreaded access. thread safety. Null Values Keys and Allows one null key and multiple null values. Does not allow null keys or null values. Optimized for multithreaded environments with minimal contention. Uses a segmented locking mechanism for better concurrency. Java 1.5 (Concurrent package) Performance Faster in single-threaded environments. Locking Mechanism Introduced In Entire map must be synchronized externally. Java 1.2
  • 24.
    Output Key Differences betweeǹ`join()` and ̀`wait()` import java.util.*; import java.util.concurrent.*; public class MapComparisonExample { public static void main(String[] args) { // HashMap example (Not thread-safe) Map hashMap = new HashMap<>(); hashMap.put("Key1", "Value1"); hashMap.put("Key2", "Value2"); System.out.println("HashMap: " + hashMap); HashMap: {Key1=Value1, Key2=Value2} ConcurrentHashMap: {Key1=Value1, Key2=Value2} ConcurrentHashMap does not allow null keys or values. } // ConcurrentHashMap example (Thread-safe) Map concurrentHashMap = new ConcurrentHashMap<>(); concurrentHashMap.put("Key1", "Value1"); concurrentHashMap.put("Key2", "Value2"); System.out.println("ConcurrentHashMap: " + concurrentHashMap); // Attempting null key and value try { hashMap.put(null, "NullValue"); concurrentHashMap.put(null, "NullValue"); } catch (Exception e) { System.out.println("ConcurrentHashMap does not allow null keys or values."); } } Q 32. What is the difference between `join()` and `wait()` in Java? Both `join()` and `wait()` are used for thread coordination in Java, but they serve different purposes and operate differently. While `join()` is specifically designed to make one thread wait for another to complete, `wait()` is used for inter-thread communication and can be customized for broader use cases. Feature Purpose Class Lock Behavior Synchronized Block Use Case Try it Yourself >> `join()` `wait()` Used for inter-thread communication, making the current thread wait until it is notified. Belongs to the ̀`Object` class. Used to wait for the completion of another thread. Belongs to the ̀`Thread` class. Does not release any locks while waiting forReleases the lock on the object it is called on and waits to be another thread to finish. notified. No need to call inside a synchronized block. Must be called within a synchronized block or method. Used to ensure one thread finishes executionUsed to implement producer-consumer or similar inter-thread before another starts. communication patterns.
  • 25.
    Example: ̀`join()` vs̀`wait()` t1.start(); Thread.sleep(100); // Ensure t1 calls wait first t2.start(); } // Demonstrating join() WorkerThread t3 = new WorkerThread(); t3.start(); System.out.println("Main thread waiting for t3 to finish..."); t3.join(); System.out.println("Main thread resumes after t3 completes."); } // Demonstrating wait() and notify() Thread t1 = new Thread(() -> resource.waitExample(), "Thread-1"); Thread t2 = new Thread(() -> resource.notifyExample(), "Thread-2"); class SharedResource { } class WorkerThread extends Thread { synchronized void waitExample() { try { System.out.println(Thread.currentThread().getName() + " is waiting..."); wait(); System.out.println(Thread.currentThread().getName() + " resumed."); } catch (InterruptedException e) { e.printStackTrace(); } } s y n c h r o n i z e d v o i d n o t i f y E x a m p l e ( ) { System.out.println(Thread.currentThread().getName() + " is notifying..."); notify(); } } public class JoinVsWaitExample { public void run() { System.out.println(Thread.currentThread().getName() + " started."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( } public static void main(String[] args) throws InterruptedException { SharedResource resource = new SharedResource(); Try it Yourself >>
  • 26.
    Output Output Example Name in Dogclass: Dog Name in Animal class: Animal Animal class method Thread-1 is waiting... Thread-2 is notifying... Thread-1 resumed. Main thread waiting for t3 to finish... Thread-3 started. Thread-3 finished. Main thread resumes after t3 completes. // Java Example: Using the super Keyword class Animal { String name = "Animal"; } c l a s s D o g e x t e n d s A n i m a l { void display() { System.out.println("Animal class method"); } String name = "Dog"; } void show() { System.out.println("Name in Dog class: " + name); System.out.println("Name in Animal class: " + super.name); // Accessing superclass variable super.display(); // Calling superclass method } p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s ) { Dog dog = new Dog(); dog.show(); } Q 34. What is a Singleton class in Java? A Singleton class in Java is a class that allows only one instance of itself to be created. It is used to restrict the instantiation of a class to a single object. This pattern is useful when you need to control access to resources, such as a database connection or a Q 33. What is the purpose of the super keyword in Java? The super keyword in Java refers to the superclass (parent class) of the current object. It is used to access members (variables, methods, and constructors) of the parent class. It is primarily used in inheritance to refer to the superclass's methods and variables and to call the constructor of the superclass. Try it Yourself >>
  • 27.
    Try it Yourself>> logging mechanism, and ensure there is only one instance of that resource. A palindrome is a word, phrase, or number that reads the same forward and backward. This question tests the candidate's understanding of string manipulation and control structures. Output Example Example: Checking Palindrome This is a Singleton class. // Java Example: Singleton Class class Singleton { private static Singleton instance; } private Singleton() { // Private constructor to prevent instantiation } p u b l i c s t a t i c S i n g l e t o n g e t I n s t a n c e ( ) { if (instance == null) { instance = new Singleton(); } return instance; } public void displayMessage() { System.out.println("This is a Singleton class."); } public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); singleton.displayMessage(); } public class Palindrome { public static void main(String[] args) { String str = "madam"; boolean isPalindrome = true; // Convert string to lowercase to ignore case sensitivity str = str.toLowerCase(); // Check if string is equal to its reverse for (int i = 0; i < str.length() / 2; i++) { if (str.charAt(i) != str.charAt(str.length() - 1 - i)) { isPalindrome = false; // If characters don't match, it's not a palindrome break; } } Q 35. Write a Java program to check if a given string is a palindrome or not.
  • 28.
    Output Example: Demonstrating Polymorphismwith Method Overriding madam is a palindrome. // Polymorphism in action animal1.sound(); // Calls Dog's sound method animal2.sound(); // Calls Cat's sound method class Animal { } class Dog extends Animal { // Method in the superclass void sound() { System.out.println("Animals make sounds."); } } c l a s s C a t e x t e n d s A n i m a l { // Overriding the method in the subclass @Override void sound() { System.out.println("Dog barks."); } } p u b l i c c l a s s P o l y m o r p h i s m E x a m p l e { // Overriding the method in the subclass @Override void sound() { System.out.println("Cat meows."); } public static void main(String[] args) { // Parent class reference pointing to child objects Animal animal1 = new Dog(); Animal animal2 = new Cat(); } if (isPalindrome) { System.out.println(str + " is a palindrome."); } else { System.out.println(str + " is not a palindrome."); } } Q 36. Design a Java program to demonstrate polymorphism using method overriding. Polymorphism in object-oriented programming allows a single interface to represent different underlying forms (data types). In Java, polymorphism is achieved through method overriding, where a subclass provides a specic implementation of a method that is already dened in its superclass. Try it Yourself >>
  • 29.
    Output Example: Demonstrating Inheritanceand Encapsulation } } Dog barks. Cat meows. class Employee { // Encapsulation: private fields private String name; private int age; private double salary; // Constructor public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } / / G e t t e r a n d S e t t e r m e t h o d s t o a c c e s s p r i v a t e f i e l d s p u b l i c S t r i n g g e t N a m e ( ) { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public void displayDetails() { System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary); } Q 37. Design a Java program to demonstrate inheritance and encapsulation. Inheritance in Java allows a class to inherit properties and behaviors from another class, promoting code reuse. Encapsulation in Java is the mechanism of wrapping data (elds) and methods into a single unit and restricting direct access to some components using access modiers. Try it Yourself >>
  • 30.
    Output Name: Alice, Age:30, Salary: 50000.0 Name: Bob, Age: 40, Salary: 80000.0 Department: IT Updated Salary of Manager: 85000.0 } // Subclass inheriting from the Employee superclass class Manager extends Employee { } public class InheritanceEncapsulationExample { private String department; // Constructor public Manager(String name, int age, double salary, String department) { super(name, age, salary); // Call superclass constructor this.department = department; } / / M e t h o d t o d i s p l a y m a n a g e r - s p e c i f i c d e t a i l s p u b l i c v o i d d i s p l a y D e t a i l s ( ) { super.displayDetails(); // Call superclass method System.out.println("Department: " + department); } } public static void main(String[] args) { // Creating Employee object Employee employee = new Employee("Alice", 30, 50000); employee.displayDetails(); // Creating Manager object Manager manager = new Manager("Bob", 40, 80000, "IT"); manager.displayDetails(); // Using Encapsulation: Updating details manager.setSalary(85000); System.out.println("Updated Salary of Manager: " + manager.getSalary()); } Q 38. What is the difference between nal, nally, and nalize in Java? nal, nally, and nalize are three distinct concepts in Java, and they serve different purposes: nalize Keyword Method nal nally / Try it Yourself >> Description Used to declare constants, prevent method overriding, and prevent inheritance of classes. Used to dene a block of code that will always execute after a try-catch block, regardless of whether an exception was thrown or not. A method called by the garbage collector just before an object is destroyed. It is used for cleanup operations before an object is discarded.
  • 31.
    Output Example Example // Java Example:transient keyword import java.io.*; class Person implements Serializable { String name; transient String password; // transient field public Person(String name, String password) { this.name = name; this.password = password; } Exception caught Finally block executed Finalize method called before object is garbage collected // Java Example: final, finally, finalize public class FinalExample { } final int MAX_VALUE = 100; // final variable void testFinally() { try { int result = 10 / 0; // Will throw exception } catch (ArithmeticException e) { System.out.println("Exception caught"); } finally { System.out.println("Finally block executed"); } } p r o t e c t e d v o i d f i n a l i z e ( ) { System.out.println("Finalize method called before object is garbage collected"); } public static void main(String[] args) { FinalExample example = new FinalExample(); example.testFinally(); // Explicitly calling finalize for demonstration example = null; System.gc(); // Requesting garbage collection } Q 39. What is the purpose of the transient keyword in Java? The transient keyword in Java is used to indicate that a particular eld should not be serialized. When an object is serialized, its non- transient elds are saved to the stream, while transient elds are ignored. This is useful when certain elds should not be part of the serialized data, such as sensitive information (e.g., passwords) or elds that are derived at runtime. Try it Yourself >>
  • 32.
    Output Example: Sorting aList of Employees by Salary Name: John Password: null import java.util.*; class Employee { private String name; private int age; private double salary; // Constructor public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } / / G e t t e r s // Deserialization FileInputStream fileIn = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Person deserializedPerson = (Person) in.readObject(); in.close(); fileIn.close(); // Serialization FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); public static void main(String[] args) throws IOException, ClassNotFoundException { Person person = new Person("John", "secret"); } System.out.println("Name: " + deserializedPerson.name); System.out.println("Password: " + deserializedPerson.password); // null, because password is transient } Q 40. Write a Java program to sort a list of objects using `Comparator`. The `Comparator` interface in Java is used to dene custom sorting logic for objects. It allows sorting objects based on different elds without modifying their class denition. Try it Yourself >>
  • 33.
    Output Example // Java Example:Static Block class StaticExample { static int x; Employees sorted by salary: Employee{name='Bob', age=25, salary=60000.0} Employee{name='Alice', age=30, salary=70000.0} Employee{name='Charlie', age=35, salary=90000.0} } public class SortEmployees { public String getName() { return name; } p u b l i c i n t g e t A g e ( ) { return age; } public double getSalary() { return salary; } / / T o d i s p l a y E m p l o y e e d e t a i l s @ O v e r r i d e p u b l i c S t r i n g t o S t r i n g ( ) { return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}"; } } public static void main(String[] args) { List employees = new ArrayList<>(); employees.add(new Employee("Alice", 30, 70000)); employees.add(new Employee("Bob", 25, 60000)); employees.add(new Employee("Charlie", 35, 90000)); // Sorting employees by salary using Comparator employees.sort(Comparator.comparingDouble(Employee::getSalary)); // Displaying sorted employees System.out.println("Employees sorted by salary:"); for (Employee e : employees) { System.out.println(e); } } Q 41. What is a static block in Java? A static block in Java is a block of code that gets executed when the class is loaded into memory, before any object of the class is created. It is used to initialize static variables or to perform any setup that should happen only once when the class is loaded. Static blocks are executed in the order in which they appear in the class. Try it Yourself >>
  • 34.
    Output Example Static block executed Valueof x: 10 // Java Example: HashMap vs TreeMap import java.util.*; // TreeMap Example Map treeMap = new TreeMap<>(); treeMap.put("Apple", "Fruit"); } public static void main(String[] args) { System.out.println("Value of x: " + x); } public class MapExample { public static void main(String[] args) { // HashMap Example Map hashMap = new HashMap<>(); hashMap.put("Apple", "Fruit"); hashMap.put("Carrot", "Vegetable"); System.out.println("HashMap: " + hashMap); // Static block to initialize static variables static { x = 10; System.out.println("Static block executed"); } Q 42. What is the difference between HashMap and TreeMap in Java? Both HashMap and TreeMap are implementations of the Map interface, but they differ in the way they store and access elements: Underlying Structure Performance Null Keys/Values Aspect Order of Elements Try it Yourself >> HashMap No order guaranteed (elements are unordered). Allows one null key and any number of null values. TreeMap Sorted according to the natural order of keys or a custom comparator. Does not allow null keys (throws NullPointerException) but allows null values. Faster for basic operations (O(1) for get and put). Hash table (uses hash function for indexing). Slower for basic operations (O(log n) for get and put due to sorting). Red-Black tree (balanced binary tree). Data
  • 35.
    Output Output Example StringBuffer: Hello World StringBuilder:Hello World HashMap: {Apple=Fruit, Carrot=Vegetable} TreeMap: {Apple=Fruit, Carrot=Vegetable} } treeMap.put("Carrot", "Vegetable"); System.out.println("TreeMap: " + treeMap); } // Java Example: StringBuffer vs StringBuilder public class StringExample { public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer("Hello"); stringBuffer.append(" World"); System.out.println("StringBuffer: " + stringBuffer); } StringBuilder stringBuilder = new StringBuilder("Hello"); stringBuilder.append(" World"); System.out.println("StringBuilder: " + stringBuilder); } Q 44. What is the difference between process and thread in Java? In Java, both processes and threads are used for concurrent execution, but they differ in the following ways: Q 43. What is the difference between StringBuffer and StringBuilder in Java? Both StringBuffer and StringBuilder are used for creating mutable strings, but there are key differences between them: Aspect Aspect Thread Safety Performance Use Case Try it Yourself >> Try it Yourself >> Process StringBuffer Thread-safe (synchronized). Slower due to synchronization overhead. Used when thread safety is required. Thread StringBuilder Not thread-safe (not synchronized). Faster as it does not have synchronization overhead. Used when thread safety is not required and performance is a priority.
  • 36.
    Try it Yourself>> Denition A process is an independent program in execution. A thread is a small unit of a process, representing a single sequence of execution. Threads share the memory space of their parent process. Lower overhead as threads share resources within the same process. Memory Each process has its own memory space. Overhead Higher overhead due to independent memory allocation and resource management. Communication Inter-process communication (IPC) is required for communication between processes. Threads can communicate directly as they share memory within the same process. The volatile keyword in Java is used to indicate that a variable's value may be changed by different threads. It ensures that any update to the variable is visible to all threads immediately without caching it in a thread's local memory. This is crucial for proper synchronization between threads and ensures the latest value is always visible across different threads. Output Example Example Thread is running... // Java Example: Volatile Keyword class SharedResource { private volatile boolean flag = false; } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // Starts the thread } public void toggleFlag() { flag = !flag; } p u b l i c v o i d c h e c k F l a g ( ) { if (flag) { System.out.println("Flag is true"); } } public static void main(String[] args) { // Java Example: Thread Example class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } Q 45. What is the use of the volatile keyword in Java?
  • 37.
    Output Output Example Flag is true //Java Example: Checked vs Unchecked Exception import java.io.*; } SharedResource resource = new SharedResource(); resource.toggleFlag(); resource.checkFlag(); } class ExceptionExample { } public static void main(String[] args) { try { // Checked exception: IOException FileReader file = new FileReader("nonexistentfile.txt"); } catch (IOException e) { System.out.println("Caught Checked Exception: " + e); } // Unchecked exception: NullPointerException String str = null; try { System.out.println(str.length()); } catch (NullPointerException e) { System.out.println("Caught Unchecked Exception: " + e); } } Q 46. What is the difference between checked and unchecked exceptions in Java? In Java, exceptions are classied into two categories: checked exceptions and unchecked exceptions. Try it Yourself >> Try it Yourself >> Aspect Denition Checked Exception Checked exceptions are exceptions that are checked at compile-time. IOException, SQLException. Must be explicitly caught or declared in the method signature. Unchecked Exception Unchecked exceptions are exceptions that are not checked at compile-time. NullPointerException, ArrayIndexOutOfBoundsException. Optional to handle or declare in the method signature. Example Handling
  • 38.
    Factorial of 5is: 120 public class LargestElement { public static void main(String[] args) { int[] numbers = {10, 25, 4, 99, 18, 54}; int largest = numbers[0]; // Assume first element is the largest // Loop through the array to find the largest element for (int i = 1; i < numbers.length; i++) { if (numbers[i] > largest) { largest = numbers[i]; // Update largest element } } System.out.println("Largest element in the array is: " + largest); public class FactorialRecursion { } // Recursive method to find factorial public static int factorial(int n) { if (n == 0) { return 1; // Base case: factorial of 0 is 1 } r e t u r n n * f a c t o r i a l ( n - 1 ) ; / / R e c u r s i v e c a l l } public static void main(String[] args) { int number = 5; System.out.println("Factorial of " + number + " is: " + factorial(number)); } Caught Checked Exception: java.io.FileNotFoundException: nonexistentfile.txt (No such file or directory) Caught Unchecked Exception: java.lang.NullPointerException Q 47. Write a Java program to find the factorial of a number using recursion. Recursion is a fundamental concept in programming where a function calls itself to solve smaller instances of the problem. This question checks your understanding of recursion. Q 48. Write a Java program to find the largest element in an array without using built-in methods. This question tests your ability to manipulate arrays and implement basic logic without relying on Java's built-in methods like `Arrays.sort()` or ̀`Collections.max()`. Try it Yourself >> Output Example: Finding Factorial Using Recursion Example: Finding the Largest Element in an Array
  • 39.
    Output Output Example } } ArrayList: [Apple, Banana] Vector:[Apple, Banana] Largest element in the array is: 99 // Java Example: ArrayList vs Vector import java.util.*; } // Vector Example List vector = new Vector<>(); vector.add("Apple"); vector.add("Banana"); System.out.println("Vector: " + vector); } public class ListExample { public static void main(String[] args) { // ArrayList Example List arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); System.out.println("ArrayList: " + arrayList); Q 50. What are the different access modiers in Java? Q 49. What is the difference between ArrayList and Vector in Java? ArrayList and Vector are both resizable array implementations of the List interface, but they have several differences: Aspect Thread Safety Growth Policy Performance Use Case Try it Yourself >> Try it Yourself >> ArrayList Not thread-safe. Resizes by 50% when full. Faster as it does not have synchronization overhead. Preferred when thread safety is not a concern. Vector Thread-safe (synchronized). Resizes by doubling its size when full. Slower due to synchronization overhead. Preferred when thread safety is required.
  • 40.
    Try it Yourself>> Modier public private protected default (No Modier) Description Accessible from any other class. Accessible only within the same class. Accessible within the same package and by subclasses. Accessible only within the same package. In Java, access modiers determine the visibility or accessibility of classes, methods, and variables. There are four main access modiers: In conclusion, preparing for a Java interview with 3 years of experience is essential for showcasing your understanding of key concepts. By reviewing the commonly asked Java interview questions and practicing with clear answers and code examples, you can strengthen your preparation and improve your condence. This article serves as a valuable resource to help you succeed in your Java interview and advance in your career. To enhance your skills further, consider enrolling in our Free Java Certication Course, which provides in-depth learning and certication to boost your career prospects. Dear learners, ScholarHat provides you with Free Tech Trendy Masterclasses to help you learn and immerse yourself in the latest trending technologies. Output Example Public Variable: 10 Private Variable: 20 Protected Variable: 30 } // Method to display the values of the variables void display() { System.out.println("Public Variable: " + publicVar); System.out.println("Private Variable: " + privateVar); System.out.println("Protected Variable: " + protectedVar); } class AccessModifiersExample { public static void main(String[] args) { AccessModifiersExample example = new AccessModifiersExample(); example.display(); // Calls the display method to print the variables } public int publicVar = 10; private int privateVar = 20; // Can be accessed anywhere // Can only be accessed within this class protected int protectedVar = 30; // Can be accessed within this class and subclasses Conclusion