Java Interview Questions
Master your interview preparation with comprehensive Q&A covering all difficulty levels
Master Java Interview Questions for QA Engineers
Context for QA Engineers: Unlike software developers, QA engineers don't need to build enterprise applications from scratch. However, you MUST understand Java fundamentals because you'll be writing test automation with Selenium, TestNG, and REST Assured. Java interviews for QA focus on practical testing knowledge, not advanced design patterns.
Key Areas Interviewers Ask About:
- OOP Concepts: Classes, inheritance, polymorphism — needed for Page Object Model
- Collections: ArrayList, HashMap — used for test data management
- Exception Handling: try-catch — critical for robust test code
- File I/O: Reading/writing test data from files
- TestNG Annotations: @Test, @BeforeEach, @DataProvider — actual testing framework
- Streams & Lambdas: Modern Java features for readable, maintainable test code
What Interviewers Want to Hear: Show that you understand Java in the context of testing. For example, when asked about inheritance, mention how you extend TestNG base classes. When asked about exceptions, explain how you handle test failures gracefully.
Common Mistakes to Avoid:
- ❌ Trying to answer like a developer ("design patterns," "microservices") instead of QA engineer
- ❌ Not mentioning TestNG or assuming they use JUnit
- ❌ Not knowing the difference between == and .equals()
- ❌ Forgetting about static methods and variables (widely used in test utilities)
Java Interview Questions - Beginner Level
What is Java?
Java is a high-level, platform-independent, object-oriented programming language. It follows "write once, run anywhere" (WORA) principle. Compiled to bytecode and executed by JVM (Java Virtual Machine).
What is the JVM (Java Virtual Machine)?
JVM is an abstract computing machine that enables a computer to run Java programs and programs written in other languages compiled to Java bytecode. It provides platform independence.
What are the main features of Java?
Object-oriented, platform-independent, multi-threaded, secure, robust, simple syntax, automatic memory management (garbage collection), rich API library, supports networking.
What are the differences between JDK, JRE, and JVM?
JVM executes bytecode. JRE (Java Runtime Environment) includes JVM + libraries. JDK (Java Development Kit) includes JRE + compiler + tools for development.
What is an object in Java?
An object is an instance of a class containing state (attributes/fields) and behavior (methods). Objects are created using the new keyword: MyClass obj = new MyClass();
What is a class in Java?
A class is a blueprint/template for creating objects. Defines attributes and methods. Example: public class Car { int speed; void drive() {} }
What are access modifiers in Java?
Control visibility: public (accessible everywhere), private (only within class), protected (within package and subclasses), default/package (within package only).
What is encapsulation?
Bundling data (attributes) and methods together, hiding internal details. Use private variables with public getter/setter methods. Improves security and maintainability.
What is inheritance?
Acquiring properties of one class (parent/super) by another (child/sub). Use extends keyword: public class Child extends Parent {}. Promotes code reusability.
What is polymorphism?
One entity taking multiple forms. Method overloading (same name, different parameters) and method overriding (child class redefines parent method).
What is method overloading?
Multiple methods with same name but different parameters (type, number, order). Resolved at compile time. Example: void add(int a, int b) {} and void add(double a, double b) {}
What is method overriding?
Child class provides specific implementation of parent's method. Same signature, different body. Resolved at runtime. Use @Override annotation.
What is an abstract class?
Class that cannot be instantiated, contains abstract methods (no implementation). Use abstract keyword. Subclasses must implement abstract methods. Example: abstract class Animal { abstract void eat(); }
What is an interface in Java?
Fully abstract class defining contract for subclasses. Contains only abstract methods and constants. Implements using implements keyword. Example: class Dog implements Animal {}
What is the difference between abstract class and interface?
Abstract class can have concrete methods, constructors, and state. Interface (traditionally) only abstract methods and constants. Java 8+ allows default methods in interfaces.
What is a constructor?
Special method called when object is created. Has same name as class, no return type. Used for initialization. Example: public MyClass() { this.name = "John"; }
What are constructor overloading and chaining?
Overloading: multiple constructors with different parameters. Chaining: calling one constructor from another using this(). Example: this("default");
What is the super keyword?
References parent class. Used to call parent's methods and constructors. Example: super.methodName(); or super();
What is the this keyword?
References current object. Used to disambiguate when local variable has same name as instance variable. Example: this.name = name;
What are data types in Java?
Primitive: byte, short, int, long, float, double, boolean, char. Reference/Object: String, Array, Classes, Interfaces.
What is the difference between primitive and reference data types?
Primitive types store actual values and have fixed size. Reference types store memory address (reference to object). Primitives are faster, references allow flexibility.
What are arrays in Java?
Fixed-size collection of elements of same type. Indexed from 0. Example: int[] arr = new int[5]; or int[] arr = {1, 2, 3};
What is a String in Java?
Immutable sequence of characters. String str = "Hello"; String is a class, not primitive. Strings are stored in string pool for efficiency.
What are String methods?
length(), charAt(), substring(), indexOf(), equals(), equalsIgnoreCase(), contains(), replace(), split(), trim(), toUpperCase(), toLowerCase().
What is ArrayList?
Dynamic array implementation of List interface. Resizes automatically. Example: ArrayList<String> list = new ArrayList<>(); list.add("item");
What is the difference between ArrayList and Array?
Arrays are fixed size, ArrayList is dynamic. Arrays are primitive, ArrayList is generic and type-safe. ArrayList has more built-in methods.
What is HashMap?
Key-value pair collection (Map interface). HashMap<String, Integer> map = new HashMap<>(); map.put("key", value); map.get("key");
What are exception types?
Checked (must be caught): IOException, SQLException. Unchecked (extends RuntimeException): NullPointerException, ArrayIndexOutOfBoundsException.
What is try-catch-finally?
try block contains risky code. catch block handles exceptions. finally block executes always (cleanup). Example: try { ... } catch (Exception e) { ... } finally { ... }
What is throws keyword?
Declares that method throws checked exception instead of handling it. Example: public void readFile() throws IOException { ... }
What is garbage collection?
Automatic memory management that removes unused objects. JVM identifies and deletes objects with no references. User calls System.gc() but doesn't guarantee immediate execution.
What is static keyword?
Makes variable/method belong to class, not instance. Static variables are shared across all instances. Static methods don't need object creation. Example: static int count = 0;
What is final keyword?
Prevents modification. Final variable (constant), final method (cannot override), final class (cannot subclass). Example: final int VAL = 10;
What is synchronized keyword?
Makes method/block thread-safe. Only one thread can access at a time. Prevents race conditions in multi-threading. Example: synchronized void method() {}
What is a package?
Directory structure for organizing classes. Prevents naming conflicts. Define: package com.example; Import: import com.example.MyClass;
What are loops in Java?
for, while, do-while, enhanced for. Example: for (int i = 0; i < 10; i++) { } or for (String item : list) { }
What are conditional statements?
if-else, switch-case. Example: if (condition) { } else { } or switch(value) { case 1: break; default: }
What are logical operators?
&& (AND), || (OR), ! (NOT). Example: if (a > 5 && b < 10) { }
What is the difference between == and equals()?
== compares references (memory address), equals() compares content. For strings: "a" == "a" may be false if different objects, but "a".equals("a") is always true.
What is the toString() method?
Returns string representation of object. Override to provide meaningful output. Default returns class name + object hash code.
What is autoboxing and unboxing?
Autoboxing converts primitive to wrapper object: int a = 5; Integer b = a; (automatic). Unboxing: Integer b = 5; int a = b; (reverse).
What are wrapper classes?
Object representations of primitive types: Integer (int), Double (double), Boolean (boolean). Allow primitives to be used as objects.
What is StringBuilder vs StringBuffer?
Both used to create mutable strings. StringBuffer is synchronized (thread-safe), StringBuilder is not. StringBuilder is faster, preferred in single-threaded code.
What is Comparable interface?
Defines natural ordering of objects. Implement compareTo() method. Used for sorting: Collections.sort(list);
What is Comparator interface?
Defines custom ordering of objects. Implement compare() method. Passed to Collections.sort(): Collections.sort(list, new MyComparator());
What are checked and unchecked exceptions?
Checked: compiler checks, must be caught (IOException, SQLException). Unchecked: runtime exceptions, not mandatory to catch (NullPointerException).
What is the split() method?
Splits string by delimiter: String[] words = sentence.split(" "); Returns array of strings.
What is null reference?
Variable that doesn't reference any object. Can be checked: if (obj == null) { }. NullPointerException thrown if null is accessed.
What is the purpose of continue and break?
break exits loop/switch. continue skips current iteration and moves to next. Example: for (...) { if (condition) continue; }
How do you read input from user?
Use Scanner: Scanner sc = new Scanner(System.in); String input = sc.nextLine(); Or use BufferedReader for files.
Java Interview Questions - Intermediate Level
What are collections in Java?
Framework for storing and manipulating groups of objects. Main interfaces: Collection (List, Set, Queue), Map. Implementations: ArrayList, HashMap, HashSet, LinkedList.
What is the difference between List, Set, and Map?
List maintains order, allows duplicates (ArrayList, LinkedList). Set doesn't allow duplicates (HashSet, TreeSet). Map stores key-value pairs (HashMap, TreeMap).
What are threads?
Lightweight process within a program. Multiple threads run concurrently. Create by extending Thread or implementing Runnable: new Thread(() -> { ... }).start();
What is the difference between Thread and Runnable?
Thread is class, Runnable is interface. Implement Runnable for multiple inheritance. Example: class Worker implements Runnable { public void run() {} }
What are thread states?
New, Runnable, Running, Waiting/Blocked, Terminated. Thread moves between states based on operations.
What is the difference between start() and run()?
start() creates new thread and calls run(). run() directly executes in current thread. Always call start(), not run().
What is a lambda expression?
Anonymous function (Java 8+). Simplified syntax for functional interfaces. Example: (a, b) -> a + b; or (x) -> x * 2;
What is a functional interface?
Interface with single abstract method. Can have default/static methods. Examples: Runnable, Callable, Comparator. Enable lambda expressions.
What are streams (Java 8)?
Functional approach to process collections. Example: list.stream().filter(x -> x > 5).map(x -> x * 2).collect(Collectors.toList());
What are generics in Java?
Provide type safety for collections. Example: List<String> list = new ArrayList<>(); Prevents ClassCastException.
What are inner classes?
Classes defined within another class. Types: static nested, non-static (inner), local, anonymous. Example: class Outer { class Inner {} }
What is an annotation?
Metadata providing information about code, not directly affecting execution. Example: @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings.
What is reflection in Java?
Ability to inspect and manipulate classes at runtime. Use Class.forName("ClassName"); Get methods, fields, constructors dynamically.
What is the difference between abstract class and concrete class?
Abstract cannot be instantiated, contains abstract methods. Concrete can be instantiated, implements all methods.
What is immutability?
Object that cannot be changed after creation. Example: String is immutable. Create immutable classes: final class, private fields, no setters.
What is the clone() method?
Creates copy of object. Implement Cloneable and override clone(). Shallow copy by default, can implement deep copy.
What is serialization?
Converting object to byte stream. Implement Serializable (marker interface). ObjectOutputStream.writeObject(obj);
What is deserialization?
Reconstructing object from byte stream. ObjectInputStream.readObject();
What is volatile keyword?
Ensures visibility of changes across threads. Volatile variable changes are immediately visible to all threads. Prevents thread caching.
What is a deadlock in threading?
Two threads waiting for each other to release resources. Prevent: lock in consistent order, use timeout, use higher-level concurrency utilities.
What are try-with-resources?
Auto-close resources (Java 7+). Example: try (FileReader fr = new FileReader("file")) { ... } //auto closes
What is the Optional class?
Container for value that may or may not be present. Example: Optional<String> opt = Optional.ofNullable(value); opt.ifPresent(System.out::println);
What are method references?
Shorthand for lambda. Example: System.out::println instead of x -> System.out.println(x);
What is the difference between interface and abstract class (Java 8+)?
Interfaces can have default methods, abstract classes can have state. Prefer interfaces for contracts, abstract classes for shared implementation.
What are default methods in interfaces?
Methods with implementation (Java 8+). Use default keyword. Allow backward compatibility when adding methods to existing interfaces.
What is NullPointerException?
Thrown when accessing member of null reference. Check before use: if (obj != null) { obj.method(); } or use Optional.
What is ClassNotFoundException?
Thrown when class is not found at runtime. Occurs with Class.forName() with invalid class name.
What is the purpose of equals() and hashCode()?
equals() compares content. hashCode() returns hash for efficient lookup in HashMap/HashSet. Override both or override neither.
What is a wildcard in generics?
? represents unknown type. Example: List<?> can hold any list. Upper bound: List<? extends Number> Lower bound: List<? super Integer>
What is the difference between StringBuilder and String concatenation?
Concatenation (+=) creates new objects each time (inefficient). StringBuilder reuses buffer (efficient). Use StringBuilder in loops.
What is LinkedHashMap?
HashMap that maintains insertion order. Useful when order matters. Example: LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
What is TreeMap?
Sorted Map implementation. Keys sorted by natural order or custom Comparator. Example: TreeMap<String, Integer> map = new TreeMap<>();
What is TreeSet?
Sorted Set implementation. Maintains ascending order. Example: TreeSet<Integer> set = new TreeSet<>();
What is the purpose of Iterator?
Interface for traversing collections. Methods: hasNext(), next(), remove(). Example: while (iterator.hasNext()) { System.out.println(iterator.next()); }
What are concurrent collections?
Thread-safe collections: ConcurrentHashMap, CopyOnWriteArrayList. Better performance than synchronized collections.
What is the difference between fail-fast and fail-safe iterators?
Fail-fast throws ConcurrentModificationException if collection modified during iteration. Fail-safe works on copy, no exception.
What is the purpose of Enum?
Type for set of constants. Example: enum Color { RED, GREEN, BLUE; } Use: Color.RED
What is the difference between new and newInstance()?
new creates object directly. newInstance() uses reflection: Class.forName("ClassName").newInstance();
What are Java modules (Java 9)?
Grouping of packages. Define in module-info.java. Improves encapsulation and dependency management for large applications.
What is the purpose of @FunctionalInterface?
Annotation marking interface as functional. Compiler ensures only one abstract method. Example: @FunctionalInterface interface MyInterface { void method(); }
What is recursion?
Method calling itself. Must have base case to avoid infinite loop. Example: factorial(n) = n * factorial(n-1) with base case n == 0
What is the Stack class?
LIFO (Last In First Out) collection. Methods: push(), pop(), peek(). Example: Stack<String> stack = new Stack<>();
What is the Queue interface?
FIFO (First In First Out) collection. Methods: offer(), poll(), peek(). Implementations: LinkedList, PriorityQueue.
What is a static initializer block?
Block executed once when class loads. Use static {} { }. Useful for initializing static variables.
What is an instance initializer block?
Block executed every time object is created. Use {} { }. Useful for common initialization code.
What is the difference between class variables and instance variables?
Class variables (static) are shared across all instances. Instance variables are unique to each object.
What is the purpose of Collections.sort()?
Sorts list using natural order or custom Comparator. Example: Collections.sort(list); or Collections.sort(list, comparator);
What is the purpose of Collections.binarySearch()?
Searches sorted list using binary search. Returns index if found, negative value if not.
What are static imports?
Importing static members directly. Example: import static java.lang.Math.*; Use Math.sqrt() without Math prefix.
What is the purpose of instanceof operator?
Checks if object is instance of class. Example: if (obj instanceof String) { ... }
Java Interview Questions - Advanced Level
What is object pooling?
Reusing objects instead of creating new ones. Improves performance by reducing garbage collection. Example: database connection pooling.
What is the purpose of weak references?
WeakReference allows garbage collection of referenced object if no strong references. Used in caches.
What is the purpose of soft references?
SoftReference cleared only when memory is low. Used for memory-sensitive caches.
What is the purpose of phantom references?
PhantomReference notifies when object is about to be garbage collected. Used for cleanup operations.
What is Spring Framework?
Popular Java framework for building applications. Provides dependency injection, AOP, transaction management. IoC container manages beans.
What is dependency injection?
Framework injects dependencies instead of object creating them. Improves testability and loose coupling. Example: @Autowired private Service service;
What are different types of dependency injection?
Constructor injection, setter injection, field injection. Constructor is preferred (immutable, testable).
What is the purpose of @Bean annotation?
Marks method as bean producer. Returns object managed by Spring container. Example: @Bean public MyService myService() { return new MyService(); }
What is AOP (Aspect-Oriented Programming)?
Separates cross-cutting concerns (logging, security) from business logic. Uses aspects, join points, advice.
What are stream operations?
Intermediate: filter(), map(), sorted(), distinct(). Terminal: collect(), forEach(), reduce(), count(). Example: list.stream().filter(x > 5).collect(Collectors.toList());
111-150. Advanced Topics (abbreviated)
111-115: Custom annotations, metaprogramming, bytecode manipulation, classloaders, memory leaks. 116-120: Performance tuning, profiling, GC optimization, JVM tuning, multithreading patterns. 121-125: Design patterns (Singleton, Factory, Observer), SOLID principles, unit testing frameworks. 126-130: Reactive programming, functional programming in Java, concurrency utilities, ExecutorService, ForkJoinPool. 131-135: Spring Boot, Spring Data, ORM frameworks (Hibernate), REST APIs, microservices. 136-140: Docker/containerization, cloud deployment, DevOps practices, CI/CD integration, monitoring. 141-145: Security practices, encryption, authentication, authorization, secure coding. 146-150: Performance benchmarking, load testing, scalability, distributed systems, system design.