top of page

Java Interview Questions for Freshers: Your Complete Preparation Guide


Landing your first Java developer role can feel overwhelming, but with the right preparation, you'll walk into that interview room with confidence. This comprehensive guide covers the most frequently asked Java interview questions for freshers, complete with detailed explanations and examples.

Table of Contents

Basic Java Concepts

Q1: What is Java and what are its key features?

Answer: Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle). Key features include:

  • Platform Independence: "Write Once, Run Anywhere" (WORA)

  • Object-Oriented: Everything is based on objects and classes

  • Automatic Memory Management: Garbage collection handles memory cleanup

  • Multi-threading: Built-in support for concurrent programming

  • Security: Strong security features and sandboxing

  • Robustness: Strong error handling and type checking

Q2: Explain the difference between JDK, JRE, and JVM.

Answer:

  • JVM (Java Virtual Machine): Runtime environment that executes Java bytecode

  • JRE (Java Runtime Environment): JVM + libraries and components needed to run Java applications

  • JDK (Java Development Kit): JRE + development tools (compiler, debugger, etc.)

Think of it as: JDK ⊃ JRE ⊃ JVM

Q3: What is bytecode in Java?

Answer: Bytecode is intermediate code generated by the Java compiler (javac) from Java source code. It's platform-independent and gets executed by the JVM. This enables Java's "write once, run anywhere" capability.

Object-Oriented Programming

Q4: What are the four pillars of OOP?

Answer:

  1. Encapsulation: Bundling data and methods together, hiding internal implementation

  2. Inheritance: Creating new classes based on existing classes

  3. Polymorphism: Same interface, different implementations

  4. Abstraction: Hiding complex implementation details, showing only essential features

Q5: Difference between abstract class and interface?

Answer:

Abstract Class

Interface

Can have concrete methods

Only abstract methods (Java 8+ allows default/static)

Can have instance variables

Only public, static, final variables

Single inheritance

Multiple inheritance supported

Can have constructors

Cannot have constructors

Access modifiers allowed

Methods are public by default

Q6: What is method overloading vs method overriding?

Answer:

Method Overloading (Compile-time polymorphism):

  • Same method name, different parameters

  • Occurs within the same class

  • Resolved at compile time


public void print(int x) { }
public void print(String s) { }
public void print(int x, int y) { }

Method Overriding (Runtime polymorphism):

  • Same method signature in parent and child class

  • Child class provides specific implementation

  • Resolved at runtime


// Parent class
public void display() { 
    System.out.println("Parent display"); 
}

// Child class
@Override
public void display() { 
    System.out.println("Child display"); 
}

Data Types and Variables

Q7: What are the primitive data types in Java?

Answer:

Type

Size

Range

Default Value

byte

8 bits

-128 to 127

0

short

16 bits

-32,768 to 32,767

0

int

32 bits

-2³¹ to 2³¹-1

0

long

64 bits

-2⁶³ to 2⁶³-1

0L

float

32 bits

IEEE 754

0.0f

double

64 bits

IEEE 754

0.0d

boolean

1 bit

true/false

false

char

16 bits

0 to 65,535

'\u0000'

Q8: Difference between == and equals()?

Answer:

  • == compares references (memory addresses) for objects, values for primitives

  • equals() compares actual content/values of objects


String s1 = new String("Hello");
String s2 = new String("Hello");
String s3 = "Hello";
String s4 = "Hello";

System.out.println(s1 == s2);        // false (different objects)
System.out.println(s1.equals(s2));   // true (same content)
System.out.println(s3 == s4);        // true (string pool)

Control Structures

Q9: Explain different types of loops in Java.

Answer:

  1. for loop: When you know the number of iterations


for(int i = 0; i < 10; i++) {
    System.out.println(i);
}
  1. while loop: When condition is checked before execution


int i = 0;
while(i < 10) {
    System.out.println(i);
    i++;
}
  1. do-while loop: When you want to execute at least once


int i = 0;
do {
    System.out.println(i);
    i++;
} while(i < 10);
  1. Enhanced for loop: For iterating collections/arrays


int[] numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
    System.out.println(num);
}

Arrays and Collections

Q10: Difference between Array and ArrayList?

Answer:

Array

ArrayList

Fixed size

Dynamic size

Can store primitives and objects

Only objects (autoboxing for primitives)

Better performance

Slightly slower due to dynamic resizing

No built-in methods

Rich set of methods


// Array
int[] arr = new int[5];
arr[0] = 10;

// ArrayList
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);

Q11: What are the main Collection interfaces?

Answer:

  • List: Ordered collection, allows duplicates (ArrayList, LinkedList, Vector)

  • Set: No duplicates allowed (HashSet, LinkedHashSet, TreeSet)

  • Queue: FIFO operations (LinkedList, PriorityQueue)

  • Map: Key-value pairs (HashMap, LinkedHashMap, TreeMap)

Exception Handling

Q12: What is exception handling and its keywords?

Answer: Exception handling manages runtime errors gracefully without crashing the program.

Keywords:

  • try: Block that might throw an exception

  • catch: Handles specific exceptions

  • finally: Always executes (cleanup code)

  • throw: Manually throws an exception

  • throws: Declares exceptions a method might throw


try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This always executes");
}

Q13: Difference between checked and unchecked exceptions?

Answer:

  • Checked Exceptions: Compile-time exceptions that must be handled (IOException, SQLException)

  • Unchecked Exceptions: Runtime exceptions, handling is optional (NullPointerException, ArrayIndexOutOfBoundsException)

String Manipulation

Q14: Why are Strings immutable in Java?

Answer: Strings are immutable for:

  • Security: Prevents modification of sensitive data

  • Thread Safety: No synchronization needed

  • String Pool Optimization: Multiple references can point to same object

  • Hashcode Consistency: Hash value doesn't change

Q15: Difference between String, StringBuilder, and StringBuffer?

Answer:

String

StringBuilder

StringBuffer

Immutable

Mutable

Mutable

Thread-safe (immutable)

Not thread-safe

Thread-safe

Slower for concatenation

Faster

Slower than StringBuilder

String pool

Heap memory

Heap memory

Memory Management

Q16: Explain Java memory structure.

Answer:

  • Heap Memory: Objects and instance variables (Young Generation, Old Generation)

  • Stack Memory: Method calls, local variables, partial results

  • Method Area: Class-level data, static variables, constant pool

  • PC Registers: Current executing instruction

  • Native Method Stacks: Native method calls

Q17: What is Garbage Collection?

Answer: Automatic memory management that removes unreferenced objects from heap memory. Main algorithms include:

  • Serial GC: Single-threaded

  • Parallel GC: Multi-threaded

  • G1 GC: Low-latency collector

  • ZGC/Shenandoah: Ultra-low latency collectors

Multithreading Basics

Q18: How do you create a thread in Java?

Answer: Two main ways:

  1. Extending Thread class:


class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
MyThread t = new MyThread();
t.start();
  1. Implementing Runnable interface:


class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread running");
    }
}
Thread t = new Thread(new MyRunnable());
t.start();

Q19: What is synchronization?

Answer: Synchronization ensures that only one thread accesses a shared resource at a time, preventing data corruption.


synchronized void method() {
    // Only one thread can execute this at a time
}

synchronized(this) {
    // Synchronized block
}

Common Coding Problems

Q20: Write a program to reverse a string.

Answer:


public class StringReverse {
    public static String reverse(String str) {
        StringBuilder sb = new StringBuilder(str);
        return sb.reverse().toString();
    }
    
    // Alternative approach
    public static String reverseManual(String str) {
        char[] chars = str.toCharArray();
        int left = 0, right = chars.length - 1;
        
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
        return new String(chars);
    }
}

Q21: Find the factorial of a number.

Answer:


public class Factorial {
    // Recursive approach
    public static long factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }
    
    // Iterative approach
    public static long factorialIterative(int n) {
        long result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }
}

Q22: Check if a number is prime.

Answer:


public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;
        
        for (int i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }
}

Interview Tips for Success

Before the Interview:

  • Practice coding on paper or whiteboard

  • Review basic algorithms and data structures

  • Prepare questions about the company and role

  • Get familiar with common IDEs (Eclipse, IntelliJ IDEA)

During the Interview:

  • Think out loud while solving problems

  • Ask clarifying questions

  • Start with a simple solution, then optimize

  • Test your code with examples

  • Be honest about what you don't know

Key Points to Remember:

  • Focus on understanding concepts, not just memorizing

  • Practice explaining technical concepts in simple terms

  • Be prepared to write code for basic programs

  • Show enthusiasm for learning and growing

  • Demonstrate problem-solving approach

Conclusion

Success in Java interviews comes from consistent practice and deep understanding of core concepts. Focus on building a strong foundation in OOP principles, basic programming constructs, and problem-solving skills. Remember, interviewers often value your thought process and approach as much as the final answer.

Keep practicing, stay curious, and approach each interview as a learning opportunity. With dedication and the right preparation, you'll land that dream Java developer role!


Good luck with your interviews!

This guide covers the most essential Java interview questions for freshers. For more advanced topics and company-specific questions, continue building your knowledge through practice and real-world project

Related Posts

See All

Comments


bottom of page