Skip to main content

Entry Java Interview Questions

Curated Entry-level Java interview questions for developers targeting entry positions. 40 questions available.

Last updated:

Java Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of Java interview questions and answers. This page contains expertly curated interview questions covering all aspects of Java, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our Java interview questions are designed to help you:

  • Understand core concepts and best practices in Java
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next Java interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic Java concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

40 questions
Q1:

What are the main features of Java?

Entry

Answer

Key Features:
• Object-Oriented
• Platform-Independent via JVM
• Robust memory management
• Multithreaded
• Secure via JVM sandboxing
Quick Summary: Java's main features: platform independence (write once, run anywhere via JVM), object-oriented, strongly typed, automatic memory management (garbage collection), multi-threading support, rich standard library, and robust exception handling. Java compiles to bytecode that runs on any JVM regardless of OS or hardware.
Q2:

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

Entry

Answer

JVM: Executes Java bytecode.
JRE: JVM + libraries needed to run Java apps.
JDK: JRE + tools for developing Java applications.
Quick Summary: JDK (Java Development Kit): full package for developing Java apps - includes compiler (javac), JRE, and dev tools. JRE (Java Runtime Environment): what end users need to run Java apps - includes JVM and standard libraries but no compiler. JVM (Java Virtual Machine): the engine that executes compiled bytecode. JDK contains JRE which contains JVM.
Q3:

What is the difference between Java and C++?

Entry

Answer

Java uses automatic garbage collection.
Java is platform-independent; C++ is platform-specific.
Java does not support direct pointers, improving security.
Quick Summary: Java vs C++: Java is interpreted (bytecode + JVM), C++ compiles to native machine code. Java has automatic garbage collection, C++ uses manual memory management. Java doesn't support multiple class inheritance (uses interfaces), C++ does. Java has no pointers (only references), C++ has full pointer arithmetic. Java is platform-independent, C++ is platform-specific by default.
Q4:

Explain object-oriented programming concepts in Java.

Entry

Answer

OOP principles:
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
Java applies these via classes, interfaces, and objects.
Quick Summary: Java OOP concepts: Encapsulation (bundle data and methods, control access via modifiers), Inheritance (a class extends another to reuse and extend behavior), Polymorphism (one interface, multiple implementations - method overriding at runtime), Abstraction (hide implementation details, expose only what's needed via abstract classes and interfaces).
Q5:

What is a class and an object in Java?

Entry

Answer

Class: Blueprint for creating objects.
Object: Instance of a class containing data and behavior.
Quick Summary: A class is a blueprint/template that defines fields (data) and methods (behavior). An object is an instance of a class - created with the new keyword. Example: class Car defines color, speed, and drive(). Each Car object is a separate instance with its own color and speed values but shares the same class methods.
Q6:

What are primitive and reference data types?

Entry

Answer

Primitive: Stores actual value (int, boolean, etc.).
Reference: Stores memory address of objects (arrays, strings, objects).
Quick Summary: Primitive types (int, double, boolean, char, byte, short, long, float) store values directly in memory - fast, no object overhead. Reference types (String, arrays, objects) store a reference (memory address) to an object on the heap. Primitives can't be null; reference types can. Primitives are passed by value; object references are also passed by value (the reference, not the object).
Q7:

What is the difference between method overloading and overriding?

Entry

Answer

Overloading: Same method name, different parameters.
Overriding: Subclass modifies inherited method.
Overloading = compile-time; overriding = runtime behavior.
Quick Summary: Overloading: same method name, different parameter types or count, resolved at compile time. Overriding: subclass provides a different implementation of a parent class method with the same signature, resolved at runtime (dynamic dispatch). Overloading is compile-time polymorphism; overriding is runtime polymorphism. Use @Override annotation to ensure you're actually overriding.
Q8:

What are constructors in Java?

Entry

Answer

Constructors initialize objects.
Can be default or parameterized.
Overloaded constructors offer multiple initialization ways.
Quick Summary: A constructor is a special method that initializes a new object. Same name as the class, no return type. Called automatically when you use new. If you don't define one, Java provides a default no-arg constructor. You can have multiple constructors (constructor overloading). Use this() to call another constructor in the same class.
Q9:

What is the difference between this and super keywords?

Entry

Answer

this: Refers to current instance.
super: Refers to parent class.
Used to call parent constructors and resolved naming conflicts.
Quick Summary: this refers to the current class instance - used to distinguish instance variables from local variables, or call other constructors (this()). super refers to the parent class - used to call parent class methods (super.method()), access parent fields (super.field), or call the parent constructor (super()) - which must be the first line in the child constructor.
Q10:

What are access modifiers in Java?

Entry

Answer

public: Accessible everywhere.
private: Inside class only.
protected: Same package + subclasses.
default: Same package.
Quick Summary: Access modifiers control visibility: private (only within the same class), default/package-private (no keyword - within the same package), protected (same package + subclasses), public (accessible everywhere). Rule of thumb: make fields private, methods public or package-private as needed. Use the most restrictive modifier that works for your use case.
Q11:

What is the difference between static and instance members?

Entry

Answer

Static: Belongs to class, shared by all objects.
Instance: Unique per object.
Static members accessed without creating object.
Quick Summary: Static members belong to the class, not instances. Static fields are shared across all instances. Static methods can be called without creating an object (Math.sqrt()). Instance members belong to each object individually - each instance has its own copy of instance fields. Static methods can't access instance fields (no "this" available).
Q12:

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

Entry

Answer

final: Constant or non-overridable.
finally: Executes after try/catch.
finalize: Called before garbage collection.
Quick Summary: final: variable can't be reassigned, method can't be overridden, class can't be extended. finally: block in try-catch that always runs (even if exception thrown) - used for cleanup (closing resources). finalize(): method called by GC before collecting an object - deprecated in Java 9, don't rely on it. All three are completely different concepts that happen to sound similar.
Q13:

What is garbage collection in Java?

Entry

Answer

Automated memory cleanup removing unused objects.
Prevents memory leaks and improves performance.
Quick Summary: Java garbage collection automatically frees memory occupied by objects with no live references. The GC runs in the background, identifies unreachable objects, and reclaims their memory. You can't force GC (System.gc() is just a hint). Modern GC algorithms (G1, ZGC, Shenandoah) minimize pause times. Memory leaks happen when you keep references to objects you no longer need.
Q14:

What are Java packages and their benefits?

Entry

Answer

Packages group related classes.
Provide organization, modularity, and access control.
Prevents naming conflicts.
Quick Summary: Packages are namespaces that organize related classes. Benefits: avoid name collisions between classes in different libraries, control access (package-private visibility), and logical grouping makes code easier to navigate. Declare with "package com.example.model" at top of file. Import classes from other packages with "import". Java standard library uses java.util, java.io, java.lang etc.
Q15:

What is an interface and how is it different from an abstract class?

Entry

Answer

Interface: Only abstract methods (older Java).
Abstract class: Can have concrete methods and fields.
Interfaces support multiple inheritance.
Quick Summary: Interface: defines a contract (method signatures), no instance fields (only constants), a class can implement multiple interfaces, methods are public abstract by default (Java 8+ allows default and static methods). Abstract class: can have concrete methods and instance fields, single inheritance only, use when related classes share common implementation. Choose interface for capabilities, abstract class for shared base implementation.
Q16:

What are Java exceptions?

Entry

Answer

Exceptions represent runtime errors.
Checked exceptions must be handled.
Unchecked exceptions don't require mandatory handling.
Quick Summary: Exceptions are runtime errors that disrupt normal program flow. Checked exceptions (IOException, SQLException) must be caught or declared with throws - checked at compile time. Unchecked exceptions (RuntimeException, NullPointerException, ArrayIndexOutOfBoundsException) don't need to be explicitly handled. Use try-catch-finally to handle exceptions. Create custom exceptions by extending Exception or RuntimeException.
Q17:

What is the difference between == and equals()?

Entry

Answer

== compares references.
equals() compares values.
equals() can be overridden for custom comparison.
Quick Summary: == compares references (memory addresses) for objects - checks if two variables point to the same object. equals() compares content/value - should be overridden to define logical equality. "abc" == "abc" may be true (string pool) but new String("abc") == new String("abc") is false. Always use equals() to compare object values, use == only for primitives or reference identity checks.
Q18:

What are wrapper classes and autoboxing/unboxing?

Entry

Answer

Wrapper classes represent primitive types as objects.
Autoboxing: primitive ? wrapper.
Unboxing: wrapper ? primitive.
Quick Summary: Wrapper classes (Integer, Double, Boolean etc.) wrap primitive types as objects so they can be used in collections and generics. Autoboxing: automatic conversion from primitive to wrapper (int to Integer). Unboxing: automatic conversion from wrapper to primitive. Watch out: unboxing a null Integer throws NullPointerException. Autoboxing in loops can create many short-lived objects.
Q19:

What are Java generics and why are they used?

Entry

Answer

Generics provide type safety.
Prevent runtime casting errors.
Used in classes, methods, and collections.
Quick Summary: Generics allow you to write type-safe code that works with any type without casting. List instead of raw List. The compiler catches type mismatches at compile time. Type parameters are erased at runtime (type erasure) - the JVM sees raw types. Benefits: no need for explicit casting, compile-time type safety, reusable algorithms that work on any type.
Q20:

What are Java collections?

Entry

Answer

Collections store groups of objects.
Common types: List, Set, Map, Queue.
Provide efficient searching, sorting, and manipulation.
Quick Summary: Java Collections Framework provides reusable data structures. Core interfaces: List (ordered, allows duplicates), Set (no duplicates), Map (key-value pairs), Queue (FIFO), Deque (double-ended). Common implementations: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap. Prefer List/Map/Set interfaces in variable types for flexibility. Use Collections utility class for sorting, searching, and synchronizing.
Q21:

What are Java 8 Lambda expressions?

Entry

Answer

Lambda expressions are anonymous functions used to implement functional interfaces.
They simplify collection processing, event handling, and reduce boilerplate.
Improve readability compared to anonymous inner classes.
Quick Summary: Lambda expressions are short anonymous functions. Syntax: (params) -> expression or (params) -> { statements }. Enables functional programming style. Used to implement functional interfaces (interfaces with one abstract method). Instead of anonymous inner class: Comparator c = (a, b) -> a.compareTo(b). Lambdas capture effectively final variables from the enclosing scope.
Q22:

Explain functional interfaces.

Entry

Answer

Functional interfaces have one abstract method (SAM).
Examples include Runnable, Callable, Comparator.
Marked with @FunctionalInterface and used with lambda expressions.
Quick Summary: Functional interfaces have exactly one abstract method (can have default and static methods). Annotate with @FunctionalInterface (optional but recommended). Built-in functional interfaces in java.util.function: Predicate (test, returns boolean), Function (apply, transforms T to R), Consumer (accept, takes T returns void), Supplier (get, returns T). Lambdas can be assigned to functional interfaces.
Q23:

What is the Streams API in Java?

Entry

Answer

Streams provide functional-style operations for processing data sequences.
Support map, filter, reduce, collect operations.
Work in sequential or parallel mode.
Quick Summary: Streams API processes collections declaratively. Pipeline: source (list.stream()) -> intermediate operations (filter, map, sorted) -> terminal operation (collect, count, forEach). Lazy evaluation - intermediate ops only run when terminal op is called. Supports method chaining. Parallel streams: list.parallelStream(). Different from java.io streams - these are for processing sequences of data.
Q24:

Difference between intermediate and terminal operations in Streams.

Entry

Answer

Intermediate operations are lazy and return streams (map, filter, sorted).
Terminal operations produce results (collect, forEach, reduce).
Pipeline allows chaining multiple intermediate operations.
Quick Summary: Intermediate operations are lazy - they don't execute until a terminal op is called and return a Stream. Examples: filter(), map(), flatMap(), sorted(), distinct(), limit(), peek(). Terminal operations trigger execution and produce a result or side effect. Examples: collect(), count(), forEach(), reduce(), findFirst(), anyMatch(), toList(). Only one terminal operation per stream pipeline.
Q25:

Explain Optional in Java.

Entry

Answer

Optional prevents null references by wrapping values.
Provides methods like isPresent(), orElse(), ifPresent().
Improves null-safety and reduces NullPointerExceptions.
Quick Summary: Optional is a container that may or may not contain a value - avoids null and NullPointerException. Create: Optional.of(value), Optional.ofNullable(valueOrNull), Optional.empty(). Consume: orElse(default), orElseGet(supplier), orElseThrow(), ifPresent(consumer), map(), flatMap(), filter(). Return Optional from methods that might not have a value. Don't use Optional as fields or method parameters.
Q26:

What is method reference in Java 8?

Entry

Answer

Method references provide shorthand for calling methods directly.
Examples: Class::staticMethod, object::instanceMethod, Class::new.
Reduce lambda verbosity.
Quick Summary: Method references are shorthand for lambdas that call an existing method. Types: ClassName::staticMethod (Static), object::instanceMethod (Bound instance), ClassName::instanceMethod (Unbound instance), ClassName::new (Constructor). Example: list.forEach(System.out::println) instead of list.forEach(s -> System.out.println(s)). More readable when the lambda just calls one method.
Q27:

Difference between map and flatMap in Streams.

Entry

Answer

map transforms each element individually.
flatMap flattens nested structures like lists inside streams.
Useful for handling nested collections.
Quick Summary: map() transforms each element with a function that returns a single value - Stream becomes Stream. flatMap() transforms each element with a function that returns a Stream, then flattens all those streams into one - useful for one-to-many transformations. Example: stream of sentences, flatMap to words: sentences.stream().flatMap(s -> Arrays.stream(s.split(" "))).
Q28:

Explain Collectors in Streams API.

Entry

Answer

Collectors accumulate stream elements into collections or other results.
Examples: toList(), toSet(), groupingBy(), joining().
Useful for aggregation and transformation.
Quick Summary: Collectors are terminal stream operations that accumulate results. Common: Collectors.toList(), toSet(), toMap(), groupingBy() (group into Map>), partitioningBy() (split into two groups by predicate), joining() (concatenate strings), counting(), summingInt(), averagingInt(). Combine with downstream collectors: groupingBy(key, counting()) counts per group.
Q29:

What are default and static methods in interfaces?

Entry

Answer

Default methods provide implementation inside interfaces.
Static methods belong to the interface and cannot be overridden.
Enhance flexibility and backward compatibility.
Quick Summary: Default methods in interfaces provide a default implementation - existing implementing classes don't need to add it. Enables interface evolution without breaking backward compatibility. Static methods in interfaces are utility methods tied to the interface (like Collections methods for Collection). Used heavily in Java 8 to add Stream/Lambda support to existing collection interfaces without breaking code.
Q30:

Explain the difference between sequential and parallel streams.

Entry

Answer

Sequential streams process elements one-by-one.
Parallel streams divide tasks into multiple threads.
Parallelism improves performance for large datasets when operations are thread-safe.
Quick Summary: Sequential streams process elements one at a time in the current thread. Parallel streams split the work across multiple threads using the ForkJoinPool. Parallel can be faster for large datasets with CPU-intensive operations but adds overhead (splitting, merging, thread management). Parallel is harmful for: small collections, I/O operations, stateful operations, or when order matters with side effects.
Q31:

How do Java 8 enhancements improve collection processing?

Entry

Answer

Lambdas reduce boilerplate.
Streams enable functional, chainable operations.
Collectors simplify grouping and aggregation.
Quick Summary: Java 8 collection enhancements: Iterable.forEach(consumer) - external loop. Collection.removeIf(predicate) - remove matching elements. List.sort(comparator). Map.forEach(), getOrDefault(), putIfAbsent(), computeIfAbsent(), merge(). Stream API for functional pipeline processing. These reduce boilerplate and enable more expressive collection processing without verbose loops.
Q32:

How do you handle exceptions in lambda expressions?

Entry

Answer

Checked exceptions must be handled inside lambda.
Custom functional interfaces can declare throws clauses.
Ensures clean functional-style error handling.
Quick Summary: Lambda bodies can only throw unchecked exceptions. To handle checked exceptions in lambdas: wrap in a try-catch inside the lambda, or create a helper functional interface that declares the checked exception, or use a utility method that wraps checked exceptions as unchecked. Alternatively, wrap the checked exception in a RuntimeException: e -> { try { ... } catch (IOException e) { throw new UncheckedIOException(e); } }
Q33:

Difference between Predicate, Function, Consumer, and Supplier.

Entry

Answer

Predicate tests conditions and returns boolean.
Function transforms input to output.
Consumer performs action without returning.
Supplier provides a value without input.
Quick Summary: Predicate: test(T t) returns boolean - used for filtering. Function: apply(T t) returns R - transformation. Consumer: accept(T t) returns void - side effects. Supplier: get() returns T - produces values. BiFunction, BiConsumer, BiPredicate handle two arguments. UnaryOperator is Function. BinaryOperator is BiFunction. These cover most functional programming needs.
Q34:

How do streams differ from traditional iteration?

Entry

Answer

Streams provide declarative processing.
Support lazy evaluation and parallelism.
Improve readability and performance for large datasets.
Quick Summary: Streams use internal iteration - you say what to do, the API handles how (can optimize, parallelize). Traditional iteration (for loop) uses external iteration - you control the loop. Streams are lazy (intermediate ops deferred), composable (chained pipelines), can be parallelized with one method call, and more declarative. Streams can only be consumed once - reuse the source to create a new stream.
Q35:

How do you group elements using Collectors?

Entry

Answer

groupingBy groups data by a key.
Supports downstream collectors like counting, summing, mapping.
Useful for analytics and reports.
Quick Summary: Collectors.groupingBy(classifier) groups stream elements into a Map>. Downstream collectors change the value: groupingBy(Person::getDept, counting()) gives Map. groupingBy(Person::getDept, toList()) is the default. Multi-level grouping: groupingBy(getDept, groupingBy(getCity)). toMap(keyMapper, valueMapper) for custom key-value extraction.
Q36:

Explain the use of peek() in streams.

Entry

Answer

peek is an intermediate operation for debugging.
Lets you inspect elements without modifying them.
Not intended for business logic.
Quick Summary: peek() is an intermediate operation that performs a side effect (like logging) for each element as it passes through, then passes the element unchanged to the next stage. Useful for debugging: stream.filter(x -> x > 0).peek(x -> log(x)).map(x -> x * 2). Don't use peek() to modify elements (it's for inspection only). Not guaranteed to run in all cases if terminal op short-circuits.
Q37:

Difference between Optional.map() and Optional.flatMap().

Entry

Answer

map transforms the wrapped value and wraps it again.
flatMap avoids nested Optionals by flattening results.
Useful with functions returning Optional.
Quick Summary: Optional.map() applies a function to the contained value if present, wrapping the result in Optional. If empty, returns empty. Optional.flatMap() applies a function that itself returns Optional and doesn't double-wrap - used to chain Optional-returning methods. map is for non-Optional-returning functions, flatMap for Optional-returning functions (avoids Optional>).
Q38:

Difference between immutable and unmodifiable collections.

Entry

Answer

Immutable collections cannot change after creation.
Unmodifiable collections prevent modification through wrapper but underlying data may still change.
Both enhance safety.
Quick Summary: Immutable collections (List.of(), Set.of(), Map.of() - Java 9+) can never be modified - add/remove/set throw UnsupportedOperationException and also disallow null elements. Unmodifiable collections (Collections.unmodifiableList()) are wrappers that reject mutations but the underlying collection can still be changed (through the original reference). Immutable is safer and allows more optimizations.
Q39:

How do you handle nulls in streams?

Entry

Answer

Use filter(Objects::nonNull) to remove nulls.
Wrap values with Optional to avoid null checks.
Prevents NullPointerExceptions.
Quick Summary: Handle nulls in streams: filter() with Objects::nonNull to remove nulls before processing. Optional.ofNullable() to wrap potentially null values. map() handles nulls poorly - returns a stream with null elements that blow up on later operations. For map values: use getOrDefault() or computeIfAbsent(). Consider using Optional upstream to avoid nulls entering the stream at all.
Q40:

What are the new Stream-related features in Java 9+?

Entry

Answer

Java 9+ adds ifPresentOrElse for Optional.
Collectors.teeing for combining results.
Factory methods like List.of(), Set.of(), Map.of().
Enhanced Stream.iterate() for bounded sequences.
Quick Summary: Java 9+ stream features: takeWhile(predicate) takes elements while condition is true then stops. dropWhile(predicate) skips elements while condition is true then takes the rest. Stream.iterate(seed, hasNext, next) finite iterate with termination condition. Stream.ofNullable(value) returns empty stream for null. These fill gaps that required workarounds in Java 8.

Curated Sets for Java

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice