05
JanJava 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.
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.
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.
Example
// Java Example: Platform Independence
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Output
Hello, Java!
Q 2. What is the difference between JDK, JRE, and JVM?
Aspect | JDK (Java Development Kit) | JRE (Java Runtime Environment) | JVM (Java Virtual Machine) | |
Purpose | Provides tools for Java development. | Provides the runtime environment for Java programs. | Executes Java bytecode. | |
Components | Includes JRE, compiler, debugger, and development tools. | Includes JVM and libraries required for execution. | Part of the JRE, performs execution and memory management. | |
Users | Used by developers to write Java programs. | Used by end-users to run Java programs. | Used internally by JRE to execute code. |
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.
Example
// Java Example: Creating an Object
class Car {
String brand;
int speed;
void display() {
System.out.println("Car brand: " + brand + ", Speed: " + speed + " km/h");
}
}
public class ObjectExample {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Tesla";
myCar.speed = 200;
myCar.display();
}
}
Output
Car brand: Tesla, Speed: 200 km/h
Q 4. What is the difference between abstraction and encapsulation in Java?
Aspect | Abstraction | Encapsulation |
Definition | Hides implementation details and shows only the functionality. | Hides the internal state of an object and protects it from unauthorized access. |
Focus | Focuses on "what" the object does. | Focuses on "how" the object's data is protected. |
Implementation | Achieved using abstract classes and interfaces. | Achieved by declaring variables private and providing getters and setters. |
Example
// Java Example: Abstraction and Encapsulation
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
System.out.println("Woof! Woof!");
}
}
public class AbstractionExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
}
Output
Woof! Woof!
Q 5. What is a constructor in Java?
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.
Example
// Java Example: Constructor
class Car {
String brand;
// Constructor
Car(String brand) {
this.brand = brand;
}
void display() {
System.out.println("Car brand: " + brand);
}
}
public class ConstructorExample {
public static void main(String[] args) {
Car myCar = new Car("Tesla");
myCar.display();
}
}
Output
Car brand: Tesla
Q 6. What is method overloading in Java?
Method overloading in Java refers to defining multiple methods in a class with the same name but different parameters (either in number or type). Overloading increases the readability of the program.
Example
// Java Example: Method Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class OverloadingExample {
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));
}
}
Output
Sum of integers: 15
Sum of doubles: 16.0
Q 7. What is method overriding in Java?
Method overriding in Java occurs when a subclass provides a specific implementation for a method already defined in its superclass. The overridden method in the subclass must have the same signature as the method in the superclass.
Example
// Java Example: Method Overriding
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
}
Output
Dog barks
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 | == Operator | equals() Method |
Comparison | Compares references (memory location). | Compares content of objects. |
Type | Used for primitives and references. | Used only for objects. |
Default Behavior | Compares memory locations by default. | Compares object data; must be overridden in custom classes. |
Example
// Java Example: == vs equals()
class Person {
String name;
Person(String name) {
this.name = name;
}
}
public class ComparisonExample {
public static void main(String[] args) {
Person p1 = new Person("John");
Person p2 = new Person("John");
System.out.println("Using ==: " + (p1 == p2)); // false
System.out.println("Using equals(): " + p1.name.equals(p2.name)); // true
}
}
Output
Using ==: false
Using equals(): 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.
Example
// Java Example: super keyword
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calling the parent class method
System.out.println("Dog barks");
}
}
public class SuperExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
}
Output
Animal makes a sound
Dog barks
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 | ArrayList | LinkedList |
Internal Structure | Backed by a dynamic array. | Backed by a doubly linked list. |
Access Speed | Faster access (O(1)) for indexed operations. | Slower access (O(n)) due to traversal. |
Insertion/Deletion | Slower insertion and deletion (O(n)) in the middle. | Faster insertion/deletion (O(1)) at both ends. |
Memory Consumption | Uses less memory compared to LinkedList. | Consumes more memory due to extra references in each node. |
Example
// 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);
}
}
Output
ArrayList: [10, 20]
LinkedList: [30, 40]
Q 11. What is the difference between String, StringBuffer, and StringBuilder?
String, StringBuffer, and StringBuilder are used to represent strings in Java. The key differences lie in their mutability and thread safety:
Aspect | String | StringBuffer | StringBuilder |
Immutability | Immutable (cannot be changed after creation). | Mutable (can be modified). | Mutable (can be modified). |
Thread Safety | Not thread-safe. | Thread-safe (synchronized methods). | Not thread-safe. |
Thread Safety | Slower due to immutability. | Slower due to synchronization overhead. | Faster than StringBuffer due to no synchronization. |
Example
// Java Example: String vs StringBuffer vs StringBuilder
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
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);
}
}
Output
String: Hello World
StringBuffer: Hello World
StringBuilder: Hello World
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 fields or constructors. It is used to achieve abstraction and multiple inheritance.
Example
// Java Example: Interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Woof");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
}
Output
Woof
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:
Let's learn the difference between Method Overloading and Method Overiding.
Aspect | Method Overloading | Method Overriding |
Definition | Defining multiple methods with the same name but different parameter lists. | Providing a new implementation for a method already defined in the parent class. |
Compile-Time vs Run-Time | Occurs at compile-time (Static Polymorphism). | Occurs at run-time (Dynamic Polymorphism). |
Inheritance | Does not require inheritance. | Requires inheritance or interface implementation. |
Return Type | It can have a different return type. | It must have the same return type. |
Access Modifier | It can have different access modifiers. | It must have the same or a more accessible access modifier. |
Example
// Java Example: Method Overloading vs Method Overriding
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding method
void sound() {
System.out.println("Dog barks");
}
// Overloading method
void sound(String soundType) {
System.out.println("Dog " + soundType);
}
}
public class OverloadOverrideExample {
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Calls parent method
Dog dog = new Dog();
dog.sound(); // Calls overridden method
dog.sound("whines"); // Calls overloaded method
}
}
Output
Animal makes a sound
Dog barks
Dog whines
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.
Example
// Java Example: this keyword
class Person {
String name;
Person(String name) {
this.name = name; // 'this' refers to the current object's instance variable
}
void display() {
System.out.println("Name: " + this.name); // 'this' used to refer to current object's field
}
}
public class ThisKeywordExample {
public static void main(String[] args) {
Person person = new Person("John");
person.display();
}
}
Output
Name: John
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.
Example
// 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");
// 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);
}
}
Output
List: [Apple, Banana]
Set: [Apple, Banana]
Map: {1=Apple, 2=Banana}
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.
Example
// Java Example: Constructor
class Car {
String model;
// Constructor
Car(String model) {
this.model = model;
}
void display() {
System.out.println("Car model: " + this.model);
}
}
public class ConstructorExample {
public static void main(String[] args) {
Car car = new Car("Tesla");
car.display();
}
}
Output
Car model: Tesla
Q 17. What is the difference between final, finally, and finalize in Java?
final, finally, and finalize are different concepts in Java:
Aspect | final | finally | finalize |
Definition | Used to define constants, prevent method overriding, or prevent inheritance. | Used to define a block of code that will always execute, regardless of exception handling. | Used to perform cleanup before an object is garbage collected. |
Usage | It can be applied to variables, methods, or classes. | Used in exception handling blocks (try-catch-finally). | Called by the garbage collector when the object is ready for a cleanup. |
Execution | Executed at compile-time. | Executed at runtime, always after the try-catch block. | Called by garbage collector, not guaranteed to be called. |
Example
// Java Example: final, finally, finalize
class MyClass {
final int x = 10;
void display() {
System.out.println("Value of x: " + x);
}
// finalize method
protected void finalize() {
System.out.println("Object is being garbage collected");
}
}
public class FinalExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
obj = null; // eligible for garbage collection
System.gc(); // Requesting garbage collection
}
}
Output
Value of x: 10
Object is being garbage collected
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 | StringBuilder | StringBuffer |
Thread Safety | Not thread-safe (faster). | Thread-safe (slower). |
Performance | Faster because it is not synchronized. | Slower due to synchronization. |
Use Case | Used when thread safety is not required. | Used when thread safety is required. |
Methods | Uses methods like append(), insert(), delete(), etc. | Same methods as StringBuilder but synchronized. |
Example
// 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);
StringBuffer sf = new StringBuffer("Hello");
sf.append(" World");
System.out.println(sf);
}
}
Output
Hello World
Hello World
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.
Example
// Java Example: Static Keyword
class Counter {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public class StaticKeywordExample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter.displayCount(); // Accessing static method without object
}
}
Output
Count: 2
Q 20. What are Java annotations, and how are custom annotations created?
- 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.
Example: Creating and Using a Custom Annotation
// 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) // Apply only to methods
@interface MyAnnotation {
String value() default "Default Message";
}
// Step 2: Annotate methods with the custom annotation
class MyClass {
@MyAnnotation(value = "Hello, World!")
public void myMethod() {
System.out.println("Executing myMethod()");
}
@MyAnnotation
public void anotherMethod() {
System.out.println("Executing anotherMethod()");
}
}
// Step 3: Access the annotation using reflection
public class AnnotationExample {
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();
}
}
}
}
Output
Method: myMethod
Annotation Value: Hello, World!
Executing myMethod()
Method: anotherMethod
Annotation Value: Default Message
Executing anotherMethod()
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 notified 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.
Example
// Java Example: Observer Design Pattern
import java.util.*;
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
class Subject {
private List observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
public class ObserverPatternExample {
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!");
}
}
Output
Observer1 received message: State Changed!
Observer2 received message: 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:
- 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.
Example
// Java Example: wait() vs sleep()
class WaitExample extends Thread {
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 class SleepWaitExample {
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.");
}
}
Output
Thread 13 is going to wait.
Thread 1 is going to sleep.
Thread 1 woke up.
Thread 13 resumed.
Q 23. What are the different types of exceptions in Java?
Exceptions in Java are categorized into two main types:
- 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.
Example
// Java Example: Checked vs Unchecked Exceptions
import java.io.*;
public class ExceptionExample {
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.");
}
}
}
Output
Checked Exception: File not found.
Unchecked Exception: Cannot divide by zero.
Q 24. What is the purpose of the finally block in Java?
The finally 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 file streams or database connections.
Example
// 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");
}
}
}
Output
Inside try block
Exception caught in catch block
Finally block executed
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.
Example
// Java Example: Factory Design Pattern
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
// Factory Class
class AnimalFactory {
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 class FactoryPatternExample {
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
}
}
Output
Woof
Meow
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 define the behavior of methods in functional programming interfaces. Lambda expressions enable the use of methods as arguments in functional programming.
Example
// Java Example: Lambda Expression
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
MathOperation add = (a, b) -> a + b;
System.out.println("Result of addition: " + add.operate(5, 3));
}
}
Output
Result of addition: 8
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 field is marked as transient, its value will not be included in the serialization process, which is particularly useful for sensitive information such as passwords.
Example
// 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;
this.name = name;
this.password = password;
}
}
public class TransientKeywordExample {
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
}
}
Output
Employee ID: 101
Employee Name: John
Employee Password: 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 configuration settings.
Example
// 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();
}
return instance;
}
public void display() {
System.out.println("Singleton Instance: " + this);
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
singleton1.display();
Singleton singleton2 = Singleton.getInstance();
singleton2.display();
}
}
Output
Singleton Instance: Singleton@5f150435
Singleton Instance: Singleton@5f150435
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 | HashSet | TreeSet |
Ordering | No ordering, elements are stored in an unordered fashion. | Maintains a natural ordering or a custom order based on a comparator. |
Performance | Faster for operations like add, remove, and contains (O(1)). | Slower due to the need to maintain order (O(log n)). |
Null Elements | Allows null elements. | Does not allow null elements. |
Sorting | Does not guarantee sorting. | Automatically sorts the elements. |
Example
// 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);
}
}
Output
HashSet: [Apple, Banana]
TreeSet: [Apple, Banana]
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.
Example
// 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
}
}
Output
// Compile-time error: variable number might not have been initialized
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.
Key Differences between `HashMap` and `ConcurrentHashMap`
Feature | HashMap | ConcurrentHashMap |
Thread Safety | Not thread-safe. Must be synchronized externally for multithreaded access. | Thread-safe. Uses internal locking mechanisms for thread safety. |
Null Keys and Values | Allows one null key and multiple null values. | Does not allow null keys or null values. |
Performance | Faster in single-threaded environments. | Optimized for multithreaded environments with minimal contention. |
Locking Mechanism | Entire map must be synchronized externally. | Uses a segmented locking mechanism for better concurrency. |
Introduced In | Java 1.2 | Java 1.5 (Concurrent package) |
Example: Using HashMap and ConcurrentHashMap
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);
// 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.");
}
}
}
Output
HashMap: {Key1=Value1, Key2=Value2}
ConcurrentHashMap: {Key1=Value1, Key2=Value2}
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.
Key Differences between `join()` and `wait()`
Feature | `join()` | `wait()` |
Purpose | Used to wait for the completion of another thread. | Used for inter-thread communication, making the current thread wait until it is notified. |
Class | Belongs to the `Thread` class. | Belongs to the `Object` class. |
Lock Behavior | Does not release any locks while waiting for another thread to finish. | Releases the lock on the object it is called on and waits to be notified. |
Synchronized Block | No need to call inside a synchronized block. | Must be called within a synchronized block or method. |
Use Case | Used to ensure one thread finishes execution before another starts. | Used to implement producer-consumer or similar inter-thread communication patterns. |
Example: `join()` vs `wait()`
class SharedResource {
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();
}
}
synchronized void notifyExample() {
System.out.println(Thread.currentThread().getName() + " is notifying...");
notify();
}
}
class WorkerThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " started.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished.");
}
}
public class JoinVsWaitExample {
public static void main(String[] args) throws InterruptedException {
SharedResource resource = new SharedResource();
// Demonstrating wait() and notify()
Thread t1 = new Thread(() -> resource.waitExample(), "Thread-1");
Thread t2 = new Thread(() -> resource.notifyExample(), "Thread-2");
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.");
}
}
Output
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.
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.
Example
// Java Example: Using the super Keyword
class Animal {
String name = "Animal";
void display() {
System.out.println("Animal class method");
}
}
class Dog extends Animal {
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
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.show();
}
}
Output
Name in Dog class: Dog
Name in Animal class: Animal
Animal class method
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 logging mechanism, and ensure there is only one instance of that resource.
Example
// Java Example: Singleton Class
class Singleton {
private static Singleton instance;
private Singleton() {
// Private constructor to prevent instantiation
}
public static Singleton getInstance() {
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();
}
}
Output
This is a Singleton class.
Q 35. Write a Java program to check if a given string is a palindrome or not.
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.
Example: Checking Palindrome
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;
}
}
if (isPalindrome) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
}
Output
madam is 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 specific implementation of a method that is already defined in its superclass.
Example: Demonstrating Polymorphism with Method Overriding
class Animal {
// Method in the superclass
void sound() {
System.out.println("Animals make sounds.");
}
}
class Dog extends Animal {
// Overriding the method in the subclass
@Override
void sound() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
// Overriding the method in the subclass
@Override
void sound() {
System.out.println("Cat meows.");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
// Parent class reference pointing to child objects
Animal animal1 = new Dog();
Animal animal2 = new Cat();
// Polymorphism in action
animal1.sound(); // Calls Dog's sound method
animal2.sound(); // Calls Cat's sound method
}
}
Output
Dog barks.
Cat meows.
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 (fields) and methods into a single unit and restricting direct access to some components using access modifiers.
Example: Demonstrating Inheritance and Encapsulation
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;
}
// Getter and Setter methods to access private fields
public String getName() {
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);
}
}
// Subclass inheriting from the Employee superclass
class Manager extends Employee {
private String department;
// Constructor
public Manager(String name, int age, double salary, String department) {
super(name, age, salary); // Call superclass constructor
this.department = department;
}
// Method to display manager-specific details
public void displayDetails() {
super.displayDetails(); // Call superclass method
System.out.println("Department: " + department);
}
}
public class InheritanceEncapsulationExample {
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());
}
}
Output
Name: Alice, Age: 30, Salary: 50000.0
Name: Bob, Age: 40, Salary: 80000.0
Department: IT
Updated Salary of Manager: 85000.0
Q 38. What is the difference between final, finally, and finalize in Java?
final, finally, and finalize are three distinct concepts in Java, and they serve different purposes:
Keyword / Method | Description |
final | Used to declare constants, prevent method overriding, and prevent inheritance of classes. |
finally | Used to define a block of code that will always execute after a try-catch block, regardless of whether an exception was thrown or not. |
finalize | A method called by the garbage collector just before an object is destroyed. It is used for cleanup operations before an object is discarded. |
Example
// 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");
}
}
protected void finalize() {
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
}
}
Output
Exception caught
Finally block executed
Finalize method called before object is garbage collected
Q 39. What is the purpose of the transient keyword in Java?
The transient keyword in Java is used to indicate that a particular field should not be serialized. When an object is serialized, its non-transient fields are saved to the stream, while transient fields are ignored. This is useful when certain fields should not be part of the serialized data, such as sensitive information (e.g., passwords) or fields that are derived at runtime.
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;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("John", "secret");
// Serialization
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
// Deserialization
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person deserializedPerson = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("Name: " + deserializedPerson.name);
System.out.println("Password: " + deserializedPerson.password); // null, because password is transient
}
}
Output
Name: John
Password: null
Q 40. Write a Java program to sort a list of objects using `Comparator`.
The `Comparator` interface in Java is used to define custom sorting logic for objects. It allows sorting objects based on different fields without modifying their class definition.
Example: Sorting a List of Employees by Salary
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;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
// To display Employee details
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}";
}
}
public class SortEmployees {
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);
}
}
}
Output
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}
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.
Example
// Java Example: Static Block
class StaticExample {
static int x;
// Static block to initialize static variables
static {
x = 10;
System.out.println("Static block executed");
}
public static void main(String[] args) {
System.out.println("Value of x: " + x);
}
}
Output
Static block executed
Value of x: 10
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:
Aspect | HashMap | TreeMap |
Order of Elements | No order guaranteed (elements are unordered). | Sorted according to the natural order of keys or a custom comparator. |
Null Keys/Values | Allows one null key and any number of null values. | Does not allow null keys (throws NullPointerException) but allows null values. |
Performance | Faster for basic operations (O(1) for get and put). | Slower for basic operations (O(log n) for get and put due to sorting). |
Underlying Data Structure | Hash table (uses hash function for indexing). | Red-Black tree (balanced binary tree). |
Example
// Java Example: HashMap vs TreeMap
import java.util.*;
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);
// TreeMap Example
Map treeMap = new TreeMap<>();
treeMap.put("Apple", "Fruit");
treeMap.put("Carrot", "Vegetable");
System.out.println("TreeMap: " + treeMap);
}
}
Output
HashMap: {Apple=Fruit, Carrot=Vegetable}
TreeMap: {Apple=Fruit, Carrot=Vegetable}
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 | StringBuffer | StringBuilder |
Thread Safety | Thread-safe (synchronized). | Not thread-safe (not synchronized). |
Performance | Slower due to synchronization overhead. | Faster as it does not have synchronization overhead. |
Use Case | Used when thread safety is required. | Used when thread safety is not required and performance is a priority. |
Example
// 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);
}
}
Output
StringBuffer: Hello World
StringBuilder: Hello World
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:
Aspect | Process | Thread |
Definition | A process is an independent program in execution. | A thread is a small unit of a process, representing a single sequence of execution. |
Memory | Each process has its own memory space. | Threads share the memory space of their parent process. |
Overhead | Higher overhead due to independent memory allocation and resource management. | Lower overhead as threads share resources within the same process. |
Communication | Inter-process communication (IPC) is required for communication between processes. | Threads can communicate directly as they share memory within the same process. |
Example
// Java Example: Thread Example
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}
Output
Thread is running...
Q 45. What is the use of the volatile keyword in Java?
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.
Example
// Java Example: Volatile Keyword
class SharedResource {
private volatile boolean flag = false;
public void toggleFlag() {
flag = !flag;
}
public void checkFlag() {
if (flag) {
System.out.println("Flag is true");
}
}
public static void main(String[] args) {
SharedResource resource = new SharedResource();
resource.toggleFlag();
resource.checkFlag();
}
}
Output
Flag is true
Q 46. What is the difference between checked and unchecked exceptions in Java?
In Java, exceptions are classified into two categories: checked exceptions and unchecked exceptions.
Aspect | Checked Exception | Unchecked Exception |
Definition | Checked exceptions are exceptions that are checked at compile-time. | Unchecked exceptions are exceptions that are not checked at compile-time. |
Example | IOException, SQLException. | NullPointerException, ArrayIndexOutOfBoundsException. |
Handling | Must be explicitly caught or declared in the method signature. | Optional to handle or declare in the method signature. |
Example
// Java Example: Checked vs Unchecked Exception
import java.io.*;
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);
}
}
}
Output
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.
Example: Finding Factorial Using Recursion
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
}
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}
Output
Factorial of 5 is: 120
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()`.
Example: Finding the Largest Element in an Array
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);
}
}
Output
Largest element in the array is: 99
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 | ArrayList | Vector |
Thread Safety | Not thread-safe. | Thread-safe (synchronized). |
Growth Policy | Resizes by 50% when full. | Resizes by doubling its size when full. |
Performance | Faster as it does not have synchronization overhead. | Slower due to synchronization overhead. |
Use Case | Preferred when thread safety is not a concern. | Preferred when thread safety is required. |
Example
// Java Example: ArrayList vs Vector
import java.util.*;
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);
// Vector Example
List vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
System.out.println("Vector: " + vector);
}
}
Output
ArrayList: [Apple, Banana]
Vector: [Apple, Banana]
Q 50. What are the different access modifiers in Java?
In Java, access modifiers determine the visibility or accessibility of classes, methods, and variables. There are four main access modifiers:
Modifier | Description |
public | Accessible from any other class. |
private | Accessible only within the same class. |
protected | Accessible within the same package and by subclasses. |
default (No Modifier) | Accessible only within the same package. |
Example
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; // Can be accessed anywhere
private int privateVar = 20; // Can only be accessed within this class
protected int protectedVar = 30; // Can be accessed within this class and subclasses
// 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);
}
}
Output
Public Variable: 10
Private Variable: 20
Protected Variable: 30
Conclusion
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 confidence. 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 Certification Course, which provides in-depth learning and certification 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.
FAQs
- Not explaining your thought process clearly.
- Writing inefficient code or not considering edge cases.
- Focusing too much on syntax and not enough on problem-solving.
- Being unprepared for both theoretical and practical questions.