
Java Interview Questions for Freshers Part 1

Table of Contents
- Difference between == and equals() method
- ArrayList and LinkedList in Java?
- Concept of Java’s Garbage Collection
- Method overloading and method overriding in Java
- What are exceptions in Java
- String, StringBuilder, and StringBuffer in Java
Preparing for a Java interview as a fresher can be both exciting and challenging. Java, being one of the most popular and widely-used programming languages, forms the backbone of many enterprise applications, web services, and Android apps. As a result, understanding the core concepts and common patterns of Java is crucial for anyone looking to start a career in software development. In interviews, candidates are often tested on their grasp of fundamental Java concepts, such as object-oriented programming, data structures, exception handling, and the differences between key Java classes and interfaces. A solid understanding of these basics can set you apart and demonstrate your readiness to tackle real-world coding challenges.
In this guide, we’ve compiled a list of essential Java interview questions tailored specifically for freshers. These questions cover a broad range of topics that are commonly encountered in technical interviews, helping you to solidify your knowledge and practice articulating your understanding of Java. Whether you’re reviewing the concepts of inheritance and polymorphism, or exploring the nuances between String
, StringBuilder
, and StringBuffer
, this collection is designed to prepare you for the kinds of questions you may face in a typical Java interview. By familiarizing yourself with these questions and practicing your responses, you’ll be better equipped to confidently showcase your Java skills to potential employers.
Join our real-time project-based Java training for comprehensive guidance on mastering Java and acing your interviews. We offer hands-on training and expert interview preparation to help you succeed in your Java career.
1. What is the difference between ==
and equals()
method in Java?
Here’s the table with the requested changes:
== Operator | equals() Method |
---|---|
Compares the reference or memory location of two objects. | Compares the contents or values of two objects. |
For primitive data types, it compares the actual values directly. | Many classes, including String , override equals() to provide content comparison. |
For object types, it checks if both references point to the same memory location. | The default implementation in Object class compares references, similar to == , but can be overridden. |
In the case of String , even if two String objects have the same content, == will return false if they are different objects. | For String , equals() returns true if both objects have the same content. |
Example: String str1 = new String("Java"); String str2 = new String("Java"); System.out.println(str1 == str2); // false | Example: System.out.println(str1.equals(str2)); // true |
Read more: Scenario Based Java Interview Questions
2. Explain the concept of inheritance in Java. How is it implemented?
Inheritance:
Inheritance is a key feature of Object-Oriented Programming (OOP) in Java, allowing a new class to inherit properties and behaviors (fields and methods) from an existing class.
It promotes code reusability and establishes a parent-child relationship between classes.
Implementation:
In Java, inheritance is implemented using the extends
keyword.
The class that is inherited is called the superclass or parent class, and the class that inherits is called the subclass or child class.
Example:
class Animal {
// Superclass
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
// Subclass
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method from Animal
dog.bark(); // Method specific to Dog
}
}
3. What is a constructor in Java? How does it differ from a regular method?
Constructor:
A constructor in Java is a special method that is used to initialize objects.
It is called automatically when an object is created.
Constructors have the same name as the class and do not have a return type, not even void
.
Difference from Regular Method:
Name: The constructor name must match the class name, whereas a method can have any name.
Return Type: Constructors do not have a return type, while methods do.
Invocation: Constructors are automatically called when an object is created, whereas methods are called explicitly using the object.
Purpose: Constructors are used to initialize the object’s state, while methods are used to perform some operation or action.
Example:
class Car {
String model;
// Constructor
Car(String modelName) {
model = modelName;
}
// Regular method
void displayModel() {
System.out.println("Model: " + model);
}
}
public class Main {
public static void main(String[] args) {
// Constructor is called here
Car car = new Car("Tesla");
// Method is called here
car.displayModel();
}
}
Explanation:
Method Call: car.displayModel()
calls the displayModel()
method on the car
object, which prints the model name "Tesla"
to the console.
Car
Class:
Field: String model
stores the model name of the car.
Constructor: Car(String modelName)
initializes the model
field with the given modelName
.
Method: void displayModel()
prints the car’s model to the console.
Main
Class:
main
Method:
Object Creation: new Car("Tesla")
creates an instance of the Car
class with the model name "Tesla"
, calling the constructor.
Read more: Arrays in Java interview Questions and Answers
4. What are the main differences between ArrayList
and LinkedList
in Java?
Here’s a table summarizing the comparison between ArrayList
and LinkedList
:
Aspect | ArrayList | LinkedList |
---|---|---|
Data Structure | Internally uses a dynamic array to store elements. It is like a resizable array. | Internally uses a doubly linked list to store elements. |
Performance | – Faster access time (O(1)) for retrieving elements, because it uses an index-based structure. – Slower in insertion and deletion (O(n)), especially in the middle of the list, because it may require shifting elements. | – Slower access time (O(n)), as it requires traversing the list. – Faster insertion and deletion (O(1)) at the beginning or middle of the list, as it only requires updating references. |
Memory Overhead | Requires less memory as it only stores data. | Requires more memory as it stores data along with references to the next and previous elements. |
Use Cases | Preferred when frequent access and iteration over the list are needed. | Preferred when frequent insertion and deletion operations are needed. |
Example:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
// Creating an ArrayList
List<String> arrayList = new ArrayList<>();
// Creating a LinkedList
List<String> linkedList = new LinkedList<>();
// Adding elements to the ArrayList
arrayList.add("Apple");
// Adding elements to the LinkedList
linkedList.add("Banana");
// Printing the contents of ArrayList
System.out.println("ArrayList: " + arrayList);
// Printing the contents of LinkedList
System.out.println("LinkedList: " + linkedList);
}
}
This code demonstrates the usage of ArrayList
and LinkedList
in Java. It begins by creating an ArrayList
and a LinkedList
of String
type. The code then adds an element to each list: “Apple” to the ArrayList
and “Bananato the
LinkedList`. After adding the elements, it prints the contents of both lists. The output will show “ArrayList: [Apple]” and “LinkedList: [Banana]”, illustrating how to use these two list implementations and how their contents are displayed.
Read more: Accenture Java interview Questions and Answers
5. Can you explain the concept of Java’s Garbage Collection? How does it work?
- Garbage Collection:
- Java provides an automatic memory management feature called Garbage Collection, which is responsible for reclaiming memory used by objects that are no longer accessible in a program.
- It helps in avoiding memory leaks by automatically removing objects that are no longer in use.
- How it Works:
- Heap Memory: When objects are created in Java, they are stored in a memory area called the heap.
- Unreachable Objects: Objects that are no longer referenced by any active thread or by any static references in the program are considered unreachable.
- Garbage Collector (GC): The Garbage Collector identifies these unreachable objects and deallocates their memory, making it available for new objects.
- GC Algorithms: Java uses different garbage collection algorithms (e.g., Mark-and-Sweep, Generational GC) to efficiently manage memory.
- Generational Approach: The heap is divided into different generations (Young, Old, and sometimes Permanent). Young generation objects are collected more frequently, and if they survive long enough, they are moved to the Old generation.
- Example: The developer does not need to manually delete objects. The following example shows how objects can become unreachable:
- In this example, when
car1
is set tonull
, theTesla
object becomes unreachable and will be eligible for garbage collection.
class Car {
String model;
// Constructor to initialize the model
Car(String model) {
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
// Creating a Car object with model "Tesla"
Car car1 = new Car("Tesla");
// Setting car1 reference to null
// The "Tesla" object becomes eligible for garbage collection
car1 = null;
}
}
What are Switch Statements in Java?
6. What is the purpose of the static
keyword in Java? Where can it be applied?
Purpose of static
: The static
keyword in Java is used to indicate that a particular member (variable, method, or nested class) belongs to the class itself, rather than to instances of the class. This means that the static
member can be accessed without creating an instance of the class.
Where it can be applied:
Static Variables:
Also known as class variables, these are shared among all instances of the class.
Static Methods:
These methods can access static variables and other static methods. They cannot access instance variables or instance methods directly.
Example:
class Car {
static int wheels;
static void displayWheels() {
System.out.println("Wheels: " + wheels);
}
}
Static Blocks:
A static block is used to initialize static variables when the class is first loaded.
Example:
class Car {
static int wheels;
static {
wheels = 4;
}
}
Static Nested Classes:
A nested class that is static can be accessed without an instance of the outer class.
Example:
class OuterClass {
static class NestedStaticClass {
void display() {
System.out.println("Static nested class");
}
}
}
7. Explain the concept of method overloading and method overriding in Java. How are they different?
Method Overloading:
Method overloading allows a class to have more than one method with the same name, as long as their parameter lists (type, number, or both) differ.
It is a compile-time polymorphism.
Example:
class MathOperations {
// Method for adding two integers
int add(int a, int b) {
return a + b;
}
// Overloaded method for adding two doubles
double add(double a, double b) {
return a + b;
}
}
In this example, the add
method is overloaded with different parameter types.
Method Overriding:
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
It is a run-time polymorphism.
Example:
class Animal {
// Method in Animal class
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the method in Dog class
@Override
void sound() {
System.out.println("Dog barks");
}
}
In this example, the Dog
class overrides the sound
method of the Animal
class.
Differences:
Overloading is about having the same method name with different signatures in the same class, while Overriding is about redefining a method from the superclass in the subclass.
Overloading is resolved at compile-time, while Overriding is resolved at runtime.
8. What is the significance of the final
keyword in Java? Provide examples of where it can be used.
Significance of final
:
The final
keyword in Java is used to restrict the modification of variables, methods, and classes. When something is declared as final
, it cannot be changed.
Where it can be used:
Final Variables:
When a variable is declared as final
, its value cannot be changed once initialized.Example:final int MAX_SPEED = 120;
Final Methods:
A method declared as final
cannot be overridden by subclasses.
Example:
class Car {
final void display() {
System.out.println("This is a final method.");
}
}
Final Classes:
A class declared as final
cannot be subclassed.
Example:
final class Car {
// class code
}
Example Usage:
class Vehicle {
// Final variable
final int maxSpeed = 120;
// Final method
final void display() {
System.out.println("Max Speed: " + maxSpeed);
}
}
// This class will cause a compilation error
// because final classes cannot be extended.
/*
class SportsCar extends Vehicle {
}
*/
In this example, the Vehicle
class has a final variable maxSpeed
, a final method display()
, and the class itself could be marked final if needed, which would prevent any subclassing.
Java Projects with Real-World Applications
9. What are exceptions in Java? How do you handle exceptions using try-catch-finally
blocks?
Exceptions in Java:
An exception is an event that disrupts the normal flow of the program’s execution. It is an object that is thrown at runtime when an error occurs.
Exceptions in Java can be broadly categorized into two types:
Checked Exceptions: These are exceptions that are checked at compile-time, like IOException
, SQLException
, etc. The programmer must handle these exceptions.
Unchecked Exceptions: These are exceptions that occur at runtime, like ArithmeticException
, NullPointerException
, etc. They are not checked at compile-time.
Handling Exceptions Using try-catch-finally
:
try
Block: The code that might throw an exception is placed inside the try
block. If an exception occurs, it is caught by the corresponding catch
block.
catch
Block: This block handles the exception. You can have multiple catch
blocks to handle different types of exceptions.
finally
Block: This block is optional and is used to execute code that must run regardless of whether an exception was caught or not (e.g., closing resources like files or database connections).
Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Explanation:
The try
block contains code that may throw an exception (in this case, dividing by zero).
The catch
block catches the ArithmeticException
and prints an appropriate message.
The finally
block runs regardless of whether the exception was caught or not, ensuring that any cleanup code (if needed) is executed.
Output:
vbnetCopy codeException
caught: / by zero Finally block executed.
My Encounter with Java Exception Handling
10. What is the difference between String
, StringBuilder
, and StringBuffer
in Java?
String
:
Immutable: String
objects are immutable, meaning once created, their values cannot be changed. Any operation that appears to modify a String
actually creates a new String
object.
Thread-Safe: Due to immutability, String
is inherently thread-safe.
Usage: Best used for fixed text or when immutability is required.
Example:
String str1 = "Hello";
String str2 = str1.concat(", World!"); // Creates a new String object
System.out.println(str2); // Prints: Hello, World!
StringBuilder
:
Mutable: StringBuilder
objects are mutable, meaning you can change their values without creating new objects.
Not Thread-Safe: StringBuilder
is not synchronized, so it is not thread-safe and should not be used in concurrent environments.
Performance: More efficient than String
for concatenation and modifications since it does not create new objects.
Usage: Preferred for scenarios where a lot of string modifications are needed, and thread-safety is not a concern.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!"); // Modifies the existing object
System.out.println(sb.toString()); // Prints: Hello, World!
StringBuffer
:
Mutable: Like StringBuilder
, StringBuffer
is mutable, allowing for modifications without creating new objects.
Thread-Safe: StringBuffer
is synchronized, making it thread-safe. Multiple threads can safely modify a StringBuffer
object.
Performance: Slightly slower than StringBuilder
due to the overhead of synchronization.
Usage: Use StringBuffer
when working with strings in a multithreaded environment.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(", World!"); // Modifies the existing object
System.out.println(sb.toString()); // Prints: Hello, World!
Summary of Differences:
String
: Immutable, thread-safe, creates new objects on modification.
StringBuilder
: Mutable, not thread-safe, faster for single-threaded scenarios.
StringBuffer
: Mutable, thread-safe, used in multithreaded environments where string modification is needed.