Skip to content

Java Interview Questions for Freshers

40 questions with answers for candidates with Freshers — 23 easy, 17 medium.

What interviewers expect: freshers

Fresher interviews focus on core Java, OOP concepts, strings, collections basics, simple SQL and two or three coding problems on arrays and strings. Interviewers check that you can write clean, working code, explain your college or training project clearly and understand the difference between common concepts like overloading and overriding, ArrayList and LinkedList, or checked and unchecked exceptions.

This set is weighted towards Java Basics and JVM (7), Strings and Exception Handling (7), Collections Framework (7), Java 8+ Features and Streams (7).

Core Java and OOP Strings and arrays coding Collections basics SQL queries and project explanation
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Why is the main method public static void?

Save to ▾
Show answer
It is public so the JVM can call it from outside the class, static so it can run without creating an object, and void because it returns nothing to the JVM; exit codes are set with System.exit(). The String[] args parameter receives command line arguments. From Java 21 onward, preview features allow simpler instance main methods for learning.
02

Count the frequency of each character in a string using Java.

Save to ▾
Show answer
A map with merge() is simple; streams also work. Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.merge(c, 1, Integer::sum); } // Streams version Map<Character, Long> f = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting())); LinkedHashMap keeps first-seen order.
03

What are the four pillars of OOP? Explain with Java examples.

Save to ▾
Show answer
Encapsulation hides data behind methods, for example private fields with getters and setters in a BankAccount class. Abstraction exposes only what is needed through abstract classes or interfaces, like a Payment interface. Inheritance lets a class reuse another, such as SavingsAccount extends Account. Polymorphism lets one reference behave differently, like a Payment variable calling pay() on a UpiPayment or CardPayment.
04

What is the difference between HashMap, LinkedHashMap and TreeMap?

Save to ▾
Show answer
HashMap gives O(1) average operations with no ordering guarantee. LinkedHashMap keeps insertion order, or access order if configured, which helps build an LRU cache. TreeMap keeps keys sorted by natural order or a Comparator with O(log n) operations and supports range methods like floorKey and headMap. HashMap allows one null key; TreeMap does not allow null keys with natural ordering.
05

How do you handle feedback that your code is too clever?

Save to ▾
Show answer
Situation: a reviewer said my one-line stream with nested collectors was hard to follow. Task: balance brevity with clarity. Action: I accepted the point, split the pipeline into named steps with small helper methods and added a comment on the business rule. Result: the next person who changed it did so without asking me, and I now aim for code a new joiner can read in one go.
06

A log file shows a NullPointerException only for some users. How do you debug it?

Save to ▾
Show answer
Start with the stack trace; since Java 14 helpful NPE messages name exactly which variable was null. Reproduce with the failing user's data, which often has an optional field missing. Fix the root cause by validating input at the boundary, using Optional for values that may be absent and annotating with @NonNull. Add a unit test for that data case so it does not return.
07

You have to process tasks in order of priority. Which collection do you use?

Save to ▾
Show answer
Use PriorityQueue, a binary heap where poll() always returns the smallest element by natural order or by a Comparator, such as Comparator.comparingInt(Task::priority). Insert and poll are O(log n) and peek is O(1). For multiple threads use PriorityBlockingQueue. Iterating a PriorityQueue does not give sorted order; only repeated poll() does.
08

What is the difference between checked and unchecked exceptions?

Save to ▾
Show answer
Checked exceptions extend Exception (but not RuntimeException) and must be caught or declared with throws, for example IOException and SQLException. Unchecked exceptions extend RuntimeException, such as NullPointerException and IllegalArgumentException, and need no declaration. Use checked exceptions for recoverable conditions callers must handle and unchecked ones for programming errors. Errors like OutOfMemoryError should not be caught.
09

How do you create a custom exception and when should you?

Save to ▾
Show answer
Extend RuntimeException for unchecked or Exception for checked, and provide constructors that accept a message and a cause so the root stack trace is kept. Create one when a domain error needs specific handling, such as InsufficientBalanceException, which a Spring @ControllerAdvice can map to an HTTP 422 response. Do not create exceptions for normal control flow.
10

What is dependency injection and why is constructor injection preferred?

Save to ▾
Show answer
Dependency injection means the container creates objects and supplies their dependencies, instead of classes creating them, which reduces coupling and helps testing. Constructor injection is preferred because dependencies can be final, objects are never half-built, required dependencies are obvious and unit tests can pass mocks without Spring. Field injection with @Autowired hides dependencies and is harder to test.
11

What is the String constant pool?

Save to ▾
Show answer
The string pool is a special area in the heap where string literals are stored once and reused. String a = "hi" and String b = "hi" point to the same object. new String("hi") creates a separate heap object, and intern() returns the pooled copy. Pooling saves memory because many strings in apps repeat, such as status codes and keys.
12

What is the difference between static and dynamic binding?

Save to ▾
Show answer
Static binding is resolved at compile time and applies to private, static and final methods and to overloaded methods, because the compiler knows exactly which method to call. Dynamic binding is resolved at runtime based on the actual object type and applies to overridden instance methods. Static methods are hidden, not overridden, so the reference type decides which one runs.
13

A team member chains Optional.get() everywhere and gets NoSuchElementException. What do you suggest?

Save to ▾
Show answer
get() on an empty Optional throws, so it brings back the same problem Optional was meant to solve. Suggest orElseThrow with a clear domain exception, orElse or orElseGet for defaults, and map or flatMap to chain safe transformations. Static analysis can flag get() without isPresent. Since Java 10 orElseThrow() without arguments is the clear name for the unchecked version.
14

What is garbage collection and how does the JVM decide an object is garbage?

Save to ▾
Show answer
Garbage collection automatically frees memory used by objects that are no longer reachable. The JVM starts from GC roots such as local variables on thread stacks, static fields and active threads, and marks every object reachable from them. Anything not marked is garbage. Because reachability is used rather than reference counting, circular references between unreachable objects are still collected.
15

What is the difference between method overloading and method overriding?

Save to ▾
Show answer
Overloading means several methods in the same class share a name but differ in parameter list; it is resolved at compile time. Overriding means a subclass provides its own version of a parent method with the same signature; it is resolved at runtime through dynamic dispatch. Return type alone cannot overload a method, while overriding allows a covariant return type.
16

What is the difference between List.of(), Arrays.asList() and Collections.unmodifiableList()?

Save to ▾
Show answer
List.of() returns a truly immutable list; add, set and remove throw exceptions and nulls are not allowed. Arrays.asList() returns a fixed-size list backed by the array: set() works and writes through to the array, but add() and remove() throw. Collections.unmodifiableList() is a read-only view, so changes to the original list are still visible through it.
17

What is the difference between an abstract class and an interface in modern Java?

Save to ▾
Show answer
An abstract class can have state (instance fields), constructors and any access modifier, and a class can extend only one. An interface has no instance state but, since Java 8, can have default and static methods, and since Java 9 private methods; a class can implement many. Use an interface for a capability contract and an abstract class to share code and state among closely related classes.
18

What is a functional interface?

Save to ▾
Show answer
A functional interface has exactly one abstract method, so it can be implemented with a lambda or method reference. It may also have default and static methods. Examples are Runnable, Comparator, and those in java.util.function: Function, Predicate, Consumer, Supplier and BiFunction. The @FunctionalInterface annotation makes the compiler enforce the single abstract method rule.
19

You need a cache that evicts the least recently used item when full. How would you build it in Java?

Save to ▾
Show answer
Extend LinkedHashMap with accessOrder set to true and override removeEldestEntry to return true when size exceeds capacity. Each get moves the entry to the end, so the eldest is the least recently used. It is not thread safe, so wrap it with synchronization for shared use. In production prefer Caffeine, which offers size and time based eviction with high concurrency.
20

How do you handle disagreement with a reviewer about your code?

Save to ▾
Show answer
Situation: a senior reviewer asked me to replace my checked exceptions with unchecked ones. Task: decide the right approach without conflict. Action: I asked for the reasons, read our codebase conventions and wrote a small comparison, then agreed because unchecked exceptions fit our global handler. Result: the change merged the same day and I learned to check team conventions before designing error handling.
21

What is the difference between JDK, JRE and JVM?

Save to ▾
Show answer
The JVM runs bytecode and handles memory, garbage collection and JIT compilation. The JRE used to be the JVM plus core libraries needed to run programs. The JDK adds development tools such as javac, jar, javadoc and jshell. Since Java 11, vendors ship only the JDK, and jlink can build a slim custom runtime for deployment.
22

How do you make a class immutable in Java?

Save to ▾
Show answer
Declare the class final, make all fields private and final, set them only in the constructor, and provide no setters. For mutable fields like a List or Date, make defensive copies in the constructor and in getters, or use List.copyOf. Immutable objects are thread safe and make good map keys. Java records give a concise way to create shallowly immutable data classes.
23

What is the difference between @Component, @Service, @Repository and @Controller?

Save to ▾
Show answer
All four mark a class as a Spring bean for component scanning. @Service and @Component are functionally the same, with @Service showing business logic intent. @Repository also enables translation of persistence exceptions into Spring DataAccessException. @Controller handles web requests and returns views, and @RestController adds @ResponseBody so return values are written as JSON.
24

An application gets StackOverflowError in a recursive method. What do you do?

Save to ▾
Show answer
StackOverflowError means the thread stack is full, usually because recursion has no proper base case or the input is very deep. First check the base case and the recursive step with the failing input. If recursion is correct but deep, such as walking a long linked structure, convert it to an iterative solution with an explicit stack. Raising -Xss is only a temporary workaround.
25

Remove duplicates from a list while keeping the original order.

Save to ▾
Show answer
A LinkedHashSet keeps first-seen order. List<String> unique = new ArrayList<>(new LinkedHashSet<>(names)); // or with streams List<String> unique2 = names.stream() .distinct() .toList(); Both rely on equals() and hashCode(), and both run in O(n) on average.
26

What are the primitive data types in Java and their sizes?

Save to ▾
Show answer
Java has eight primitives: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2 bytes, UTF-16 code unit) and boolean (true or false, size JVM dependent). Primitives store values directly and have default values when used as fields, for example 0 for int and false for boolean. Each has a wrapper class such as Integer.
27

A @Transactional method is not rolling back after an exception. What could be wrong?

Save to ▾
Show answer
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
28

What is Optional and how should it be used?

Save to ▾
Show answer
Optional is a container that may or may not hold a value, used mainly as a method return type to show that a result can be absent, for example findById. Use map, filter, orElse, orElseGet and orElseThrow instead of calling get() blindly. Do not use Optional for fields, parameters or collections, and prefer orElseGet when the default is costly to create.
29

What is the difference between intermediate and terminal operations in streams?

Save to ▾
Show answer
Intermediate operations like filter, map, sorted and distinct return a new stream and are lazy; nothing runs until a terminal operation is called. Terminal operations like collect, forEach, reduce, count and findFirst trigger processing and produce a result. Laziness lets streams fuse steps into a single pass and short-circuit, so findFirst on filtered data stops early.
30

What does effectively final mean for lambdas?

Save to ▾
Show answer
A lambda can use a local variable from the enclosing method only if that variable is final or effectively final, meaning it is never reassigned after initialisation. Lambdas capture the value, not the variable, so this avoids confusing behaviour and races. To accumulate results, use a stream collector or an AtomicInteger instead of changing a captured local.
31

A counter shared between threads shows wrong totals. How do you fix it?

Save to ▾
Show answer
count++ is not atomic; two threads can read the same value and both write the same result, so updates are lost. Use AtomicInteger.incrementAndGet(), which uses CAS, or LongAdder for very high contention, as it spreads updates over cells. A synchronized method also works but is slower. volatile alone does not fix it because it gives visibility, not atomicity.
32

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

Save to ▾
Show answer
start() asks the JVM to create a new thread and then calls run() on that new thread, so the code executes concurrently. Calling run() directly is just a normal method call on the current thread, so no new thread is created. Calling start() twice on the same Thread throws IllegalThreadStateException.
33

How does HashSet work internally?

Save to ▾
Show answer
HashSet is backed by a HashMap. Each element you add becomes a key in that map with a shared dummy object as the value. So uniqueness depends entirely on the element's hashCode() and equals(), and operations are O(1) on average. LinkedHashSet uses a LinkedHashMap to keep insertion order, and TreeSet uses a TreeMap to keep elements sorted.
34

Explain the main memory areas of the JVM.

Save to ▾
Show answer
The heap stores all objects and is shared by threads; it is managed by the garbage collector. Each thread has its own stack holding frames with local variables and partial results. Metaspace (native memory since Java 8) stores class metadata. There are also the program counter register and native method stacks. StackOverflowError comes from the stack and OutOfMemoryError usually from heap or metaspace.
35

Write a stream to partition numbers into even and odd lists.

Save to ▾
Show answer
partitioningBy splits into a map with true and false keys. Map<Boolean, List<Integer>> parts = nums.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0)); List<Integer> evens = parts.get(true); List<Integer> odds = parts.get(false); Both keys are always present, even if one list is empty, unlike groupingBy.
36

What is the difference between Comparable and Comparator?

Save to ▾
Show answer
Comparable defines a class's natural ordering through compareTo() inside the class, such as String sorted alphabetically. Comparator is a separate object with compare(), so you can define many orderings without changing the class. Java 8 made Comparator easy: Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getName). TreeMap and sort methods accept either.
37

Why did you choose Java for your career?

Save to ▾
Show answer
Situation: in college I tried several languages for projects. Task: I wanted one that leads to stable, well paid work. Action: I found Java powers banking, ecommerce and enterprise backends, has strong tooling and a huge job market, so I built two Spring Boot projects and practised DSA in Java. Result: I am confident in the language and keen to keep learning modern features like records and virtual threads.
38

Use CountDownLatch to wait for three worker threads to finish.

Save to ▾
Show answer
The main thread waits until the count reaches zero. CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { try { doWork(); } finally { latch.countDown(); } }).start(); } latch.await(30, TimeUnit.SECONDS); System.out.println("all done"); countDown in finally makes sure the latch is released even on error.
39

Find the first non-repeating character in a string.

Save to ▾
Show answer
Count in one pass, then scan again in order. public static char firstUnique(String s) { int[] cnt = new int[128]; for (char c : s.toCharArray()) cnt[c]++; for (char c : s.toCharArray()) { if (cnt[c] == 1) return c; } return '_'; } Two passes, O(n) time and O(1) extra space for ASCII input.
40

How do you handle a situation where you made a wrong technical decision?

Save to ▾
Show answer
Situation: I chose eager loading for a reporting entity to save time, and later pages became slow. Task: own and fix it. Action: I told my lead, measured the impact, switched associations to lazy with targeted fetch joins and added query count tests. Result: performance recovered within a sprint and I now review fetch strategy in every design discussion.

Frequently asked questions

What is asked in Java interviews for Freshers?

Fresher interviews focus on core Java, OOP concepts, strings, collections basics, simple SQL and two or three coding problems on arrays and strings. Interviewers check that you can write clean, working code, explain your college or training project clearly and understand the difference between common concepts like overloading and overriding, ArrayList and LinkedList, or checked and unchecked exceptions.

How many questions should I practise before a Java interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for Freshers?

Focus first on Core Java and OOP, Strings and arrays coding, Collections basics, SQL queries and project explanation.