Interview Questions Technology

30 Java Basics Interview Questions and Answers

30 Java basics interview questions and answers with examples for beginners and experienced Java developers

Java remains one of the most popular programming languages used in enterprise applications, backend services, Android development, and more. In interviews, core Java fundamentals are always tested thoroughly. Below are 30 common Java basics interview questions, each followed by a clear theoretical explanation and a working code example (where applicable).

I break them into thematic groups (Java fundamentals, OOP, collections & strings, exception & memory, concurrency, etc.) to help you structure your understanding.


Part 1: Java Fundamentals & Syntax

1. What is Java? What are its key features?

Theory
Java is a high-level, class-based, object-oriented programming language designed to be portable, secure, and robust. Its motto is “Write Once, Run Anywhere” (WORA) — you compile source code into platform-independent bytecode, which runs on any machine with a compatible JVM.

Key features include:

  • Platform independence via bytecode + JVM
  • Automatic memory management via Garbage Collection
  • Strongly typed (static typing)
  • Rich standard library (APIs)
  • Multithreading support
  • Exception handling
  • Security (sandboxing, access controls)
  • Robustness (null safety checks, exception mechanisms)

Example

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Compile with javac Hello.java, run with java Hello. The same .class file can work on Windows, macOS, or Linux (provided a JVM exists).


2. What is the difference between JDK, JRE, and JVM?

Theory

  • JVM (Java Virtual Machine): The runtime engine that executes Java bytecode. It is platform-specific (each OS has its own JVM).
  • JRE (Java Runtime Environment): Contains the JVM + standard libraries + supporting files. It’s what you need to run Java programs.
  • JDK (Java Development Kit): Contains JRE + developer tools (compiler javac, debugger, etc.). Use JDK to develop Java programs.

Example
When you run javac MyClass.java, you are using the compiler provided by the JDK. When you run java MyClass, you are invoking the JVM (via the JRE) to execute bytecode.


3. Why is Java called platform independent?

Theory
Java source code is compiled into bytecode (a .class file), which is the same across platforms. The JVM on each platform interprets or JIT-compiles that bytecode into native machine code at runtime. This separation decouples source and target machine architectures, making Java platform independent.

Example
You compile on Windows:

C:\> javac Hello.java → Hello.class

Then copy Hello.class to Linux and run:

$ java Hello

It works without recompiling, thanks to platform-specific JVMs.


4. What does public static void main(String[] args) mean?

Theory

  • public — access modifier: the JVM must be able to call main from outside the class.
  • static — no need to instantiate the class to call this method; JVM calls it directly.
  • void — the method returns nothing.
  • main — the entry point name exact signature recognized by JVM.
  • String[] args — command-line arguments passed as an array of strings.

Example

public class Demo {
    public static void main(String[] args) {
        System.out.println("Number of args: " + args.length);
        for (String s : args) {
            System.out.println(s);
        }
    }
}

If you run java Demo one two three, output:

Number of args: 3
one
two
three

5. What are primitive types and reference types in Java?

Theory

  • Primitive types are built-in types (e.g. int, long, byte, short, char, float, double, boolean). They store actual values, not references, and have default zero (or false) values when instance fields.
  • Reference types (classes, interfaces, arrays) refer to objects in memory. A variable holds a pointer (reference) to the object in the heap.

Example

int x = 5;
Integer y = new Integer(5);  // y is a reference type

Here x stores the literal 5. y stores a reference to an Integer object in heap.


6. What is autoboxing and unboxing?

Theory

  • Autoboxing is automatic conversion from primitive to its wrapper class.
  • Unboxing is automatic conversion from wrapper to primitive.

Example

int a = 10;
Integer b = a;     // autoboxing: primitive to wrapper
int c = b + 5;     // unboxing: wrapper to primitive

Before Java 5, you had to explicitly convert, e.g., Integer b = Integer.valueOf(a); or int c = b.intValue();.


7. What is the difference between == and .equals() in Java?

Theory

  • == checks reference equality: whether two reference variables point to the same object.
  • .equals() checks logical equality (object content), if the class overrides it appropriately.

Example

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);        // false — different objects
System.out.println(s1.equals(s2));   // true — same content

Also:

String s3 = "hello";
String s4 = "hello";
System.out.println(s3 == s4);        // true — string literal pool

Because literal strings are interned.


Part 2: Object-Oriented Programming (OOP) Concepts

8. What are the four main pillars of OOP in Java?

Theory

  1. Encapsulation — bundling data (fields) and methods together, and controlling access via access modifiers (private, public, etc.).
  2. Inheritance — a class (subclass) inherits properties and behavior from a parent class.
  3. Polymorphism — ability of one interface to be used for different underlying forms (method overloading, method overriding).
  4. Abstraction — hiding implementation details and exposing only essential features (via interfaces, abstract classes).

Example

class Animal {
    public void speak() {
        System.out.println("Animal speaks");
    }
}

class Dog extends Animal {  // inheritance
    @Override
    public void speak() {   // polymorphism (override)
        System.out.println("Dog barks");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();  // dynamic polymorphism
        a.speak();  // prints "Dog barks"
    }
}

Encapsulation is shown when fields are private and accessed via getters/setters. Abstraction via abstract classes or interfaces.


9. What is the difference between abstract class and interface (pre-Java 8 and post-Java 8)?

Theory

  • Abstract class may contain both abstract (without body) and concrete (with body) methods, instance fields, constructors, etc. A class can extend only one abstract class (single inheritance).
  • Interface (before Java 8): only abstract methods and constants (public static final). From Java 8 onward, interfaces can have default and static methods with implementations, and from Java 9, private methods. From Java 8+, interfaces are more powerful.

Which to choose:

  • Use abstract class when you want to provide base implementation and share code.
  • Use interface when you want to define a contract that many unrelated classes may implement.

Example (Java 8+)

interface Vehicle {
    void go();  // abstract method

    default void start() {  // default method
        System.out.println("Vehicle is starting");
    }

    static void info() {    // static method
        System.out.println("Vehicles are used for transport");
    }
}

abstract class Car implements Vehicle {
    // can override or leave default methods
}

class Sedan extends Car {
    @Override
    public void go() {
        System.out.println("Sedan going");
    }
}

public class Demo {
    public static void main(String[] args) {
        Vehicle v = new Sedan();
        v.start();        // prints default
        v.go();
        Vehicle.info();   // static interface method
    }
}

10. What is method overloading and method overriding?

Theory

  • Overloading: multiple methods in the same class with same name but different parameter lists (type or count).
  • Overriding: in subclass, you provide a new implementation of a method inherited from parent class (same method signature). Used for runtime polymorphism.

Example (Overloading & Overriding)

class Calculator {
    // Overloading
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}

class AdvancedCalc extends Calculator {
    @Override
    int add(int a, int b) {
        System.out.println("Subclass add");
        return super.add(a, b);
    }
}

public class Demo {
    public static void main(String[] args) {
        Calculator c = new AdvancedCalc();
        System.out.println(c.add(2, 3));        // calls overridden version
        System.out.println(c.add(2.5, 3.7));    // calls overloaded version
    }
}

11. What is this keyword in Java?

Theory
this is a reference to the current object. It is used to:

  • Distinguish instance variables from parameters with the same name.
  • Invoke other constructors in the same class (constructor chaining via this(...)).
  • Pass current object as parameter.

Example

class Point {
    private int x, y;

    public Point(int x, int y) {
        this.x = x;  // `this.x` is instance field; `x` is parameter
        this.y = y;
    }

    public void demo() {
        System.out.println("Point: " + this.x + ", " + this.y);
    }
}

public class Demo {
    public static void main(String[] args) {
        new Point(5, 7).demo();
    }
}

12. What is inheritance? What types exist in Java?

Theory
Inheritance is a mechanism by which a class acquires features (methods and variables) of another class. The class that inherits is called subclass or child class; the class being inherited from is parent or superclass.

Java supports single inheritance for classes (each class can have only one direct superclass). But inheritance via interfaces allows multiple inheritance of type.

Types:

  • Single inheritance
  • Multilevel inheritance
  • Hierarchical inheritance
  • Multiple inheritance (via interfaces only)
  • Hybrid (combination via interfaces/abstract classes)

Example (multilevel & hierarchical)

class A { void f() { System.out.println("A"); } }
class B extends A { void g() { System.out.println("B"); } }
class C extends B { void h() { System.out.println("C"); } }

class D extends A { void j() { System.out.println("D"); } }

public class Demo {
    public static void main(String[] args) {
        C c = new C();
        c.f(); c.g(); c.h();
        D d = new D();
        d.f(); d.j();
    }
}

Part 3: Strings, Arrays, Collections, Generics

13. How is String immutable in Java? What is the string pool?

Theory
Immutable means once created, you cannot change the content of a String object. Any modification (e.g. substring, concat) results in creation of a new String object.

String Pool (or intern pool) is a special area in the heap memory (or permgen/Metaspace region historically) where Java stores string literals. When you create a string literal "hello", Java first checks if it exists in the pool; if yes, reuse the reference; else, create it. This helps memory optimization.

Example

String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);  // true, same literal
String s3 = new String("hello");
System.out.println(s1 == s3);  // false
System.out.println(s1.equals(s3));  // true

Here s1 and s2 refer to same interned literal. s3 is a new object.


14. What is the difference between String, StringBuilder, and StringBuffer?

Theory

  • String is immutable.
  • StringBuilder is mutable, non-synchronized (not thread-safe), faster for single-threaded operations.
  • StringBuffer is like StringBuilder but synchronized (thread-safe), slower due to synchronization overhead.

Use StringBuilder when you need to build or mutate strings in one thread; StringBuffer in multithreaded contexts.

Example

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString());  // "Hello World"

StringBuffer sbf = new StringBuffer("Hi");
sbf.append(" there");
System.out.println(sbf.toString()); // "Hi there"

15. How do you reverse a string in Java?

Theory
Several approaches:

  • Convert to char[] and swap characters.
  • Use StringBuilder or StringBuffer’s reverse() method.
  • Use recursion.

Example (using StringBuilder)

public static String reverse(String input) {
    if (input == null) return null;
    return new StringBuilder(input).reverse().toString();
}

public static void main(String[] args) {
    System.out.println(reverse("abcd"));  // prints "dcba"
}

16. How do you convert between arrays and collections (e.g., List)?

Theory
Java provides utility methods in java.util.Arrays and Collections. For example, Arrays.asList(...), toArray(), copying between them, etc.

Example

String[] arr = { "a", "b", "c" };
// Convert array to List
List<String> list = Arrays.asList(arr);
// Convert list to array
String[] newArr = list.toArray(new String[0]);

Note: The list returned by Arrays.asList is a fixed-size list backed by the original array; you cannot add/remove from it (unsupported operations).


17. What are generics in Java? Why use them?

Theory
Generics allow parameterization of types, so you can create classes, interfaces, and methods that operate on typed objects while providing compile-time type safety and eliminating casts.

For example, List<String> ensures you can only add String objects and retrieve them without casting.

Generics also support bounds (upper, lower) and wildcards (e.g. <? extends T>, <? super T>).

Example

List<Integer> li = new ArrayList<>();
li.add(10);
// li.add("abc");  // compile-time error

Integer x = li.get(0); // no cast needed

You can define generic methods:

public static <T> T echo(T input) {
    return input;
}

18. What is a Map, Set, List in Java Collections? Key differences?

Theory

  • List: ordered collection allowing duplicates (e.g. ArrayList, LinkedList).
  • Set: collection that disallows duplicates, unordered or sorted (e.g. HashSet, TreeSet).
  • Map: key-value pairs, keys unique, values can duplicate (e.g. HashMap, TreeMap).

Example

List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");  // duplicate allowed

Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple");  // duplicate ignored

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Alice", 35);  // key “Alice” updated

19. What is the difference between ArrayList and LinkedList?

Theory

  • ArrayList is backed by a resizable array. It offers constant-time access (get), but insertion/removal in middle is costly (shifting).
  • LinkedList is implemented as a doubly-linked list. Insertions/removals are efficient given a reference, but random access (get(i)) is slower (O(n)).

Choose ArrayList when you need fast random access; LinkedList when insertions/deletions in middle are frequent.

Example

List<String> al = new ArrayList<>();
al.add("a"); al.add("b");

List<String> ll = new LinkedList<>();
ll.add("a"); ll.add("b");

To remove the first element:

al.remove(0);   // shifts subsequent elements
ll.remove(0);   // adjusts pointers

Part 4: Exception Handling, Memory, Garbage Collection

20. What is exception handling in Java? Checked vs unchecked exceptions?

Theory
Exception handling is a mechanism to handle runtime errors so the normal flow of the application is maintained. It uses try, catch, finally, and throw/throws.

  • Checked exceptions are checked at compile time (must be caught or declared) — e.g. IOException, SQLException.
  • Unchecked exceptions are runtime exceptions that are not checked at compile time — e.g. NullPointerException, ArrayIndexOutOfBoundsException.

Example

public static void readFile(String fname) throws IOException {
    FileReader fr = new FileReader(fname);  // may throw FileNotFoundException (checked)
    // ...
}

public static void main(String[] args) {
    try {
        readFile("nonexistent.txt");
    } catch (IOException e) {
        System.out.println("File not found: " + e.getMessage());
    } finally {
        System.out.println("Clean-up if needed");
    }
}

21. What is finally block? What about try-with-resources?

Theory

  • A finally block is executed after try/catch whether or not exception occurs, often used for cleanup (closing streams, releasing resources).
  • Try-with-resources (Java 7+) auto-closes resources implementing AutoCloseable after use, even if exception is thrown, reducing boilerplate.

Example (try-with-resources)

public void readFile(String fname) {
    try (BufferedReader br = new BufferedReader(new FileReader(fname))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        System.out.println("Error: " + e.getMessage());
    }
    // br is automatically closed
}

22. How does garbage collection work in Java? What are GC roots?

Theory
Garbage collection (GC) is the process by which Java runtime reclaims memory by removing objects that are no longer reachable. You cannot explicitly free memory (no free or delete). The JVM uses various GC algorithms (Mark-and-Sweep, generational GC, etc.)

GC roots are references from which the GC starts marking reachable objects (e.g. local variables in stack frames, static fields, JNI references). Anything not reachable from these roots is eligible for collection.

You may influence GC via System.gc() (suggested) or JVM flags, but not guaranteed.

Example

public class Demo {
    public static void main(String[] args) {
        Demo d = new Demo();
        d = null;
        System.gc();  // suggests garbage collection
        System.out.println("Done");
    }
}

Although d becomes eligible for GC, it may not be collected immediately.


23. What is the difference between stack memory and heap memory in Java?

Theory

  • Stack memory stores local variables, method call frames, and references. It is fast, of fixed size, and managed in LIFO order.
  • Heap memory is the runtime data area from which objects are allocated. It is larger and dynamic; objects live until GC reclaims them.

Local primitive variables and references live on stack; the actual object data lives in heap.

Example

public void foo() {
    int x = 10;          // x in stack
    MyClass obj = new MyClass();  // obj reference in stack, object in heap
}

Once foo() returns, its frame is popped, local variables are destroyed; object continues until no references remain.


24. What is the difference between shallow copy and deep copy?

Theory

  • Shallow copy duplicates top-level object, but references inside (to other objects) remain pointing to the same.
  • Deep copy duplicates entire object graph (all nested objects), so no shared references.

Shallow copy is easier but can cause side effects; deep copy is safer but more complex (often via serialization, clone methods, or manually).

Example

class Address {
    String city;
    Address(String c) { city = c; }
}

class Person implements Cloneable {
    String name;
    Address addr;

    @Override
    protected Person clone() throws CloneNotSupportedException {
        Person p = (Person) super.clone();  // shallow copy
        p.addr = new Address(this.addr.city); // deep copy for nested object
        return p;
    }
}

public static void main(String[] args) throws Exception {
    Person p1 = new Person();
    p1.name = "Alice";
    p1.addr = new Address("Mumbai");

    Person p2 = p1.clone();
    p2.addr.city = "Delhi";

    System.out.println(p1.addr.city);  // if shallow copy, would also show "Delhi"
}

Part 5: Multithreading & Concurrency (Basics)

25. How do you create a thread in Java? What is Runnable vs Thread?

Theory
Two standard ways:

  1. Extend Thread class and override run()
  2. Implement Runnable interface (with run() method) and pass to a Thread object (preferred, allows better design).

Runnable is functional (can be a lambda in Java 8+). Also, Callable is similar but can return a value and throw exceptions.

Example (Runnable approach)

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task is running in " + Thread.currentThread().getName());
    }
}

public class Demo {
    public static void main(String[] args) {
        Thread t = new Thread(new MyTask());
        t.start();
        System.out.println("Main thread done");
    }
}

26. What is synchronized keyword? What is intrinsic lock / monitor?

Theory
synchronized ensures that only one thread can execute a block/method at a time on the same object (monitor lock). Java objects have an intrinsic lock (or monitor). When a thread enters a synchronized block/method, it acquires the lock; other threads attempting to enter must wait until lock is released.

You can synchronize:

  • instance methods (synchronized void m())
  • static methods (synchronized static void m())
  • code block (synchronized(obj) { ... })

Example

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();
        Runnable r = () -> {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        };
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println(c.getCount());  // ideally 2000
    }
}

27. What is deadlock? How to prevent it?

Theory
Deadlock is a condition when two or more threads are waiting for each other to release locks, causing all to block forever. It typically happens with nested locks.

Prevention strategies:

  • Avoid nested locks or minimize synchronized regions.
  • Use a consistent order of acquiring locks.
  • Use timeout (tryLock in java.util.concurrent.locks).
  • Use lock ordering, lock hierarchy, or higher-level concurrency APIs.

Example (simplified deadlock)

class A { synchronized void foo(B b) { b.bar(); } }
class B { synchronized void bar() { System.out.println("In B.bar"); } }

public class Demo {
    public static void main(String[] args) {
        A a = new A(); B b = new B();
        new Thread(() -> a.foo(b)).start();
        new Thread(() -> b.bar()).start();
        // Could lead to deadlock when one thread holds A and waits for B, the other holds B and waits for A
    }
}

28. What is volatile keyword?

Theory
volatile is a field modifier which ensures that changes to this variable are always visible to other threads (variable stored in main memory, not in thread-local cache). It also prevents certain reorderings.

Use volatile for flags or simple shared variables when you don’t need atomic operations (for atomic operations, use AtomicInteger, synchronized, etc.).

Example

class Flag {
    volatile boolean done = false;

    public void writer() {
        done = true;
    }
    public void reader() {
        if (done) {
            System.out.println("Done is true");
        }
    }
}

Without volatile, one thread might never see the updated value of done.


Part 6: Miscellaneous & Code/Algorithm

29. How to swap two numbers without a temporary variable in Java?

Theory
You can swap using arithmetic or bitwise XOR trick:

  • Arithmetic: a = a + b; b = a - b; a = a - b;
  • XOR (only valid for integers, careful with overflow): a = a ^ b; b = a ^ b; a = a ^ b;

Example (arithmetic)

int a = 5, b = 10;
a = a + b;  // 15
b = a - b;  // 5
a = a - b;  // 10
System.out.println("a=" + a + ", b=" + b);  // prints "a=10, b=5"

30. Write a Java program to check if a string is a palindrome.

Theory
A palindrome reads the same backward and forward. You can compare characters symmetrically or reverse and compare.

Example

public static boolean isPalindrome(String s) {
    if (s == null) return false;
    int i = 0, j = s.length() - 1;
    while (i < j) {
        if (s.charAt(i) != s.charAt(j)) return false;
        i++; j--;
    }
    return true;
}

public static void main(String[] args) {
    System.out.println(isPalindrome("radar"));  // true
    System.out.println(isPalindrome("hello"));  // false
}

If you’ve mastered the Java basics, it’s time to level up your skills.
Check out our in-depth guide on advanced Java interview questions to prepare for senior-level roles and real-world coding challenges:
https://teckforge.com/2025/10/07/top-20-advanced-java-interview-questions-and-answers-with-examples/

Leave a Reply

Your email address will not be published. Required fields are marked *