THE MODN CHRONICLES

Interview Prep

Interview Questions on Java for Freshers — OOPs, Collections, Strings, and What TCS/Infosys Actually Ask

Java is the default language for campus placements in India. TCS, Infosys, Wipro, Cognizant, and HCL all test Java fundamentals in their technical rounds. Here are the exact questions they ask freshers — with the depth they expect.

Java code on a developer screen during interview preparation

Java remains the most tested language in Indian campus placements. Every service company interview starts with Java fundamentals.

Java for Freshers — What Interviewers Actually Test

If you are a B.Tech/BCA/MCA student preparing for campus placements in India, Java is the language you will be tested on. Even if you learned Python in college, service companies like TCS, Infosys, and Wipro default to Java for their technical rounds. The reason is simple — Java is the backbone of enterprise software in India, and these companies need developers who can work on Java projects from day one.

Fresher Java interviews follow a predictable pattern: OOPs concepts (always first), String handling, Collections framework, exception handling, and basic multithreading. If you know these five topics well, you can clear 90% of service company technical rounds.

This guide covers the actual Java questions asked to freshers in Indian campus placements — organized by topic, with code examples and the exact answers interviewers expect.

In Indian campus placements, Java OOPs questions are asked in 100% of technical rounds. If you cannot explain the four pillars with code examples, the interview ends there.

OOPs Concepts — The Foundation

Every single Java fresher interview starts with OOPs. The four pillars — Encapsulation, Inheritance, Polymorphism, and Abstraction — are non-negotiable. You need to explain each with a code example.

Q1: What are the four pillars of OOPs? Explain with examples.

// 1. ENCAPSULATION — bundling data + methods, hiding internals
class BankAccount {
    private double balance; // hidden from outside
    
    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    public double getBalance() {
        return balance; // controlled access
    }
}

// 2. INHERITANCE — child class inherits from parent
class Animal {
    void eat() { System.out.println("eating"); }
}
class Dog extends Animal {
    void bark() { System.out.println("woof"); }
}
// Dog has both eat() and bark()

// 3. POLYMORPHISM — same method, different behavior
// Compile-time (overloading):
class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}
// Runtime (overriding):
class Animal {
    void sound() { System.out.println("generic sound"); }
}
class Cat extends Animal {
    void sound() { System.out.println("meow"); }
}

// 4. ABSTRACTION — hiding complexity, showing essentials
abstract class Shape {
    abstract double area(); // what, not how
}
class Circle extends Shape {
    double radius;
    double area() { return Math.PI * radius * radius; }
}

Q2: What is the difference between abstract class and interface?

Abstract Class                Interface
─────────────────────         ─────────────────────
Can have constructors         No constructors
Can have instance variables   Only constants (static final)
Can have concrete methods     Only abstract methods (pre-Java 8)
Single inheritance only       Multiple interfaces allowed
"extends" keyword             "implements" keyword
Partial abstraction           Full abstraction

// Since Java 8, interfaces can have:
// - default methods (with body)
// - static methods
// Since Java 9: private methods in interfaces

// When to use which:
// Abstract class → shared state + partial implementation
// Interface → contract/capability (Serializable, Comparable)

Q3: Can you override a static method? Can you overload a static method?

Override: No. Static methods belong to the class, not the instance. If a child class defines the same static method, it is method hiding, not overriding. The method called depends on the reference type, not the object type.

Overload: Yes. You can have multiple static methods with the same name but different parameters in the same class.

String Handling Questions

String questions are the second most common topic in fresher Java interviews. The String pool concept and immutability are tested in every interview.

Q4: Why are Strings immutable in Java?

// Strings are immutable — once created, cannot be changed

String s1 = "Hello";
s1.concat(" World"); // creates NEW string, s1 unchanged
System.out.println(s1); // "Hello" (not "Hello World")

// To capture the change:
s1 = s1.concat(" World"); // s1 now points to new object

// WHY immutable?
// 1. String Pool — multiple references share same object
//    If mutable, changing one would affect all
// 2. Security — used in class loading, network connections
// 3. Thread safety — immutable = inherently thread-safe
// 4. Hashcode caching — String caches its hashcode
//    (used in HashMap keys)

Q5: What is the difference between String, StringBuilder, and StringBuffer?

String         → Immutable, thread-safe, slow for concatenation
StringBuilder  → Mutable, NOT thread-safe, fast
StringBuffer   → Mutable, thread-safe (synchronized), slower

// When to use:
// String → when value does not change
// StringBuilder → single-threaded string manipulation
// StringBuffer → multi-threaded string manipulation

// Performance example:
// String concatenation in a loop creates N objects
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i; // creates 1000 String objects!
}

// StringBuilder creates only 1 object
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i); // modifies same object
}
String result = sb.toString();

Q6: What is the String pool? What is the difference between == and .equals()?

// String pool: special memory area in heap
// Stores one copy of each unique string literal

String s1 = "Hello";     // goes to pool
String s2 = "Hello";     // reuses from pool
String s3 = new String("Hello"); // new object in heap

s1 == s2;      // true (same reference in pool)
s1 == s3;      // false (different objects)
s1.equals(s3); // true (same content)

// Rule: ALWAYS use .equals() for String comparison
// == compares references (memory addresses)
// .equals() compares actual content

Collections Framework

Collections questions test whether you understand data structures in Java. The most common questions are about ArrayList vs LinkedList, HashMap internals, and when to use which collection.

Q7: ArrayList vs LinkedList — when to use which?

ArrayList                    LinkedList
─────────────────────        ─────────────────────
Dynamic array internally     Doubly linked list
Fast random access O(1)      Slow random access O(n)
Slow insert/delete O(n)      Fast insert/delete O(1)
Less memory overhead         More memory (node pointers)
Better for read-heavy        Better for write-heavy

// Use ArrayList when:
// - You access elements by index frequently
// - You mostly add to the end
// - Read operations >> write operations

// Use LinkedList when:
// - You insert/delete from middle frequently
// - You use it as a Queue or Deque
// - Order of insertion matters more than access speed

// In practice: ArrayList is used 95% of the time

Q8: How does HashMap work internally?

// HashMap stores key-value pairs using hashing

// Internal structure:
// Array of buckets (Node[])
// Each bucket is a linked list (or tree if > 8 nodes)

// put(key, value) process:
// 1. Calculate hashCode() of key
// 2. Find bucket index: hash & (n-1)
// 3. If bucket empty → store directly
// 4. If bucket has entries → check equals()
//    - Same key → update value
//    - Different key → add to linked list (collision)

// get(key) process:
// 1. Calculate hashCode() → find bucket
// 2. Traverse bucket, use equals() to find exact key

// Java 8 improvement:
// If a bucket has > 8 entries, linked list → red-black tree
// This improves worst-case from O(n) to O(log n)

// Default capacity: 16, Load factor: 0.75
// Resizes (doubles) when 75% full

Q9: What is the difference between HashMap, LinkedHashMap, and TreeMap?

HashMap        → No order guaranteed, O(1) operations
LinkedHashMap  → Maintains insertion order, O(1) operations
TreeMap        → Sorted by key (natural/comparator), O(log n)

// HashSet vs LinkedHashSet vs TreeSet → same pattern
// HashSet uses HashMap internally (values are dummy)

// When to use:
// HashMap → default choice, fastest
// LinkedHashMap → need insertion order (LRU cache)
// TreeMap → need sorted keys (range queries)
Students preparing for Java interview

Java Collections and OOPs together cover 70% of fresher technical interview questions at Indian IT companies.

Exception Handling

Q10: What is the difference between checked and unchecked exceptions?

Checked Exceptions (compile-time):
- Must be handled (try-catch) or declared (throws)
- IOException, SQLException, FileNotFoundException
- Compiler forces you to handle them

Unchecked Exceptions (runtime):
- Not required to handle
- NullPointerException, ArrayIndexOutOfBoundsException
- Extend RuntimeException

// Exception hierarchy:
// Throwable
//   ├── Error (OutOfMemoryError, StackOverflowError)
//   └── Exception
//         ├── Checked (IOException, SQLException)
//         └── RuntimeException (unchecked)
//               ├── NullPointerException
//               ├── ArrayIndexOutOfBoundsException
//               └── ArithmeticException

Q11: What is the difference between final, finally, and finalize?

final:
- Variable → cannot be reassigned
- Method → cannot be overridden
- Class → cannot be extended (String is final)

finally:
- Block that ALWAYS executes after try-catch
- Used for cleanup (closing connections, files)
try {
    // risky code
} catch (Exception e) {
    // handle error
} finally {
    // ALWAYS runs (even if exception occurs)
    connection.close();
}

finalize():
- Method called by garbage collector before destroying object
- Deprecated since Java 9 — do not use
- Use try-with-resources instead

Basic Multithreading

Q12: What is the difference between Thread class and Runnable interface?

// Method 1: Extend Thread class
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
new MyThread().start();

// Method 2: Implement Runnable interface
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable running");
    }
}
new Thread(new MyRunnable()).start();

// Runnable is preferred because:
// 1. Java allows only single inheritance
//    (extending Thread blocks extending other classes)
// 2. Runnable separates task from thread management
// 3. Can be used with ExecutorService (thread pools)

Q13: What is the difference between start() and run()?

start() creates a new thread and calls run() in that new thread. run() called directly executes in the current thread — no new thread is created. This is one of the most common trick questions. Always use start() to actually create a new thread.

Preparation Plan for Freshers

Week 1: OOPs + Strings

Master the four pillars with code examples. Practice String pool, immutability, and StringBuilder questions. Write code for each concept — do not just read.

Week 2: Collections + Exception Handling

Understand HashMap internals, ArrayList vs LinkedList, and when to use which collection. Practice try-catch-finally and checked vs unchecked exceptions.

Week 3: Multithreading + Java 8 Basics

Learn Thread vs Runnable, synchronized keyword, and basic thread lifecycle. For Java 8: lambda expressions, Stream API basics, and Optional class.

Week 4: Mock Interviews + Coding Practice

Practice explaining concepts out loud. Solve 2-3 Java coding problems daily (reverse string, find duplicates, sort array). Use AI mock interviews to simulate real pressure.

Company-Wise Java Question Focus

TCS NQT

  • • OOPs definitions
  • • String methods
  • • Array operations
  • • Basic coding

Infosys InfyTQ

  • • Collections framework
  • • Exception handling
  • • Interface vs abstract
  • • Medium coding

Wipro/Cognizant

  • • OOPs with code
  • • HashMap internals
  • • Multithreading basics
  • • SQL + Java combo

Practice Java Interview Questions with AI

Get asked real Java fresher interview questions and receive instant feedback. Practice OOPs, Collections, and String questions in a simulated interview environment.

Free · AI-powered feedback · Campus placement questions