204 Java Interview Questions for Freshers [2026]
204 Java interview questions for freshers with beginner level answers, output prediction puzzles, coding round problems, HR answers and a 4 week plan.
On this page
This guide is written for your first Java interview. It assumes you have finished a Java course or a degree module and have not yet worked a paid engineering job. Every answer is pitched at the depth a fresher is actually expected to give, which is shorter and plainer than what a senior candidate would say.
That calibration is the point. Freshers lose offers less often for shallow knowledge than for two other things: reciting a memorized paragraph they cannot then explain, and freezing on a twelve line program that prints something unexpected. So this page covers the language fundamentals, then the parts of a fresher interview that concept lists ignore, namely output prediction, the coding round, your academic projects, and the HR round.
Where a question has more depth available than a fresher needs, the answer links to the page that goes further. Use those links after your fundamentals feel solid, not before.
How Java Fresher Interviews Work#
What do companies actually test in a fresher Java interview?#
Three things, in this order: whether you can write a small correct program, whether you understand what your own code does, and whether you will be straightforward to train. Nobody expects production experience. They are checking that the fundamentals are real rather than memorized, because a fresher who understands twenty concepts properly is easier to grow than one who has skimmed two hundred.
What are the rounds in a typical fresher hiring process?#
Most companies run some subset of the following. Smaller companies compress it into two rounds, while large service companies run all of them across several weeks.
| Round | Format | What it filters for |
|---|---|---|
| Online assessment | Timed aptitude, Java multiple choice, output prediction, one or two coding problems | Volume filter. Speed and accuracy on basics |
| Coding round | Shared editor or whiteboard, one or two problems | Whether you can turn a problem into working code |
| Technical interview | 45 to 60 minutes of concept questions plus your project | Depth behind the definitions |
| Managerial or second technical | Your project in detail, how you work, hypotheticals | Communication and ownership |
| HR round | Motivation, location, joining date, expectations | Fit and logistics, rarely elimination |
How is a service company interview different from a product company interview?#
Service companies hire in large batches, so they lean on standardized online assessments and ask broad definitional questions across many topics. Product companies hire fewer people and weight the coding round far more heavily, often with a data structures problem harder than anything in a service company test. Prepare breadth for the first and problem solving for the second.
How much Java do you need to know as a fresher?#
The fundamentals on this page, plus the ability to write around forty lines of correct code without an IDE autocompleting for you. You do not need JVM internals, the concurrency utilities, or framework internals. Knowing those areas exist and roughly what they solve is enough at this stage.
Which Java version should a fresher learn on?#
Java 21 or Java 25, both long term support releases. Java 27 is the newest release, generally available since September 2026, but it is a short support release that almost no company runs in production. Many real codebases are still on Java 17 or Java 21, which is why interviewers rarely ask about anything newer.
What does LTS mean and why does it matter in an interview?#
LTS stands for long term support. Vendors ship a feature release every six months but designate one every two years for extended support. Java 17, 21 and 25 are LTS releases, and the next is expected to be Java 29 around September 2027, which you can check against the Oracle Java SE support roadmap. It matters because the honest answer to "which version do you use" is an LTS version, and answering "the latest one" signals you have not seen a real codebase.
Do freshers get asked about Spring or Hibernate?#
Sometimes, usually as a single awareness question rather than a deep one. If your resume lists Spring Boot, expect to be asked what dependency injection means and to walk through one endpoint you built, and skim Spring Boot Interview Questions for the handful you are likely to get. The same applies to Hibernate if your project used JPA. If your resume lists neither, you will rarely be pushed there. Never list a framework you cannot discuss for two minutes.
How long should your answers be?#
Aim for 30 to 45 seconds: a one sentence definition, one concrete detail or example, then stop. Stopping is the part freshers get wrong. A short correct answer invites a follow up question, which is how a conversation builds, whereas a three minute monologue hides whether you understood what was asked.
What should you do when you do not know an answer?#
Say you do not know, then say what you do know that is adjacent, then stop. "I have not used serialization, but I understand it is about converting an object into bytes so it can be stored or sent" is a good answer. Guessing confidently is the worst option, because the interviewer now has to work out whether anything else you said was invented.
Is it acceptable to ask the interviewer to clarify a question?#
Yes, and it reads as competence rather than weakness. "When you say thread safe, do you mean the collection itself or the whole method?" shows you know the term has more than one scope. Answering the wrong question confidently costs you more than one clarifying sentence does.
What should a fresher resume contain for a Java role?#
One page: education, two or three projects with the stack named and one line on what you personally built, relevant coursework, and any internship. Skip the skills bar charts and the rated proficiency stars, because an interviewer reads "Java 4/5" as an invitation to find the gap. List only what you can defend.
Java Language Basics#
What is Java?#
A general purpose, object oriented, statically typed programming language. Source is compiled to bytecode rather than to machine code, and that bytecode runs on the Java Virtual Machine. It is used heavily for backend services, Android applications and large enterprise systems.
Why is Java called platform independent?#
Because the compiler produces bytecode rather than instructions for one specific processor and operating system, so any machine with a JVM for its platform can run the same .class file. The usual phrasing is "write once, run anywhere", and the honest footnote is that the bytecode is portable while the JVM itself is not.
What is bytecode?#
The intermediate instruction set that javac produces, stored in .class files. It is neither readable machine code nor Java source, but a compact format designed for the JVM to verify and execute. You can inspect it with javap -c, which is worth doing once so the term stops being abstract.
What is the JVM?#
The Java Virtual Machine is the program that loads your .class files, verifies the bytecode, and executes it. It also manages memory for you, which is why Java has no manual free call. Different vendors ship different JVMs, and HotSpot is the most common.
What is the difference between the JDK and the JRE?#
The JDK is the development kit: compiler, debugger, tooling and a runtime. The JRE is the runtime alone, enough to run a program but not to compile one. As a fresher you install the JDK. Worth adding that a standalone JRE is no longer shipped separately for modern Java, so this is now more of an interview question than a daily decision.
What does the javac command do?#
It compiles .java source files into .class bytecode files and reports compile time errors such as type mismatches and missing symbols. Running javac Hello.java produces Hello.class.
What does the java command do?#
It starts a JVM and runs the class you name, calling its main method. You pass the class name rather than the file name, so it is java Hello and not java Hello.class. Since Java 11 it can also run a single source file directly, compiling it in memory.
Is Java compiled or interpreted?#
Both, which is what the question is fishing for. Source is compiled ahead of time to bytecode, and the JVM then interprets that bytecode while also compiling the frequently executed parts to native code as the program runs. Saying only compiled, or only interpreted, is scored as a half answer.
What is the JIT compiler?#
The just in time compiler is the part of the JVM that notices which methods run often and compiles those to native machine code during execution. This is why a Java program frequently gets faster in its first seconds of life. You need only the idea as a fresher, not the tiering details.
What is the structure of a minimal Java program?#
public class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}
A class declaration, a main method with that exact signature, and statements inside it. Historically the file name had to match the public class name, and although modern Java also allows a compact source file form, you should match the names in an interview.
Why is the main method written as public static void?#
It is public so the JVM can call it from outside the class, static so it can be called without first creating an object, and void because the JVM does not use a return value. The String[] args parameter receives command line arguments. Deviate from that signature and the JVM reports that it could not find or load the main class.
Can a program have more than one main method?#
Yes. Every class may have its own, and you choose which one runs by naming that class on the command line. You can also overload main within a class, but the JVM will only ever use the String[] version as an entry point.
What is a package?#
A namespace that groups related classes and controls access, declared on the first line of a file as package com.example.billing;. Packages map to folders on disk and prevent name clashes, which is why two libraries can each contain a class called Logger.
What does the import statement do?#
It lets you refer to a class by its short name instead of its fully qualified name, so import java.util.List; means you can write List rather than java.util.List. It copies no code and does not affect program size, being purely a compile time convenience. Classes in java.lang, such as String, are available without an import.
What is the classpath?#
The list of locations where the compiler and JVM look for classes, set with -cp or the CLASSPATH variable. When you see ClassNotFoundException or NoClassDefFoundError, a wrong classpath is the usual cause. Maven and Gradle build it for you, which is why most developers rarely set it by hand.
What are the access modifiers in Java?#
Four levels, from most open to most closed: public everywhere, protected within the same package and in subclasses, package private which is what you get by writing nothing, and private within the same class only. The habit worth stating is that fields start private and you widen access only when something outside genuinely needs it. For how these interact with inheritance and API design, see Java OOP Interview Questions.
What is the difference between a statement and an expression?#
An expression produces a value, such as a + b or list.size(). A statement is a complete instruction, such as an assignment or an if block. The distinction became concrete in modern Java, where switch exists in both forms.
What are comments and which forms does Java have?
Three: // to end of line, /* */ spanning lines, and /** */ Javadoc comments that tooling turns into API documentation. Javadoc is the one worth knowing by name, because it is the only form that produces output rather than being discarded by the compiler.
Variables, Data Types and Operators
What are the primitive types in Java?
Eight: byte, short, int, long, float, double, char and boolean. They hold values directly rather than references, cannot be null, and are not objects. Everything else in Java is a reference type.
How much memory does each primitive type use?
| Type | Size | Default | Typical use |
|---|---|---|---|
| byte | 8 bit | 0 | Raw binary data |
| short | 16 bit | 0 | Rare in practice |
| int | 32 bit | 0 | The default whole number |
| long | 64 bit | 0L | Timestamps, IDs, counters |
| float | 32 bit | 0.0f | Rare, precision too low |
| double | 64 bit | 0.0d | The default decimal |
| char | 16 bit | '\u0000' | A single UTF-16 unit |
| boolean | Not specified | false | True or false |
Note the boolean row. The specification does not fix its size, so saying "one bit" is a common fresher mistake. In practice the JVM usually uses a full byte or word.
What is the difference between int and Integer?
int is a primitive holding a number directly; Integer is a class wrapping one. Only Integer can be null, be placed in a collection, or have methods called on it. The practical consequence is that an Integer can throw NullPointerException when unboxed, which an int never can.
What does autoboxing do and where does it bite you?
Autoboxing is the compiler automatically converting a primitive to its wrapper, and unboxing is the reverse. It is why List<Integer> list = new ArrayList<>(); list.add(5); compiles even though 5 is an int. The trap to mention is that unboxing a null wrapper throws NullPointerException at a line that contains no visible method call.
What is type casting?
Converting a value from one type to another. Widening happens implicitly because no information can be lost, as in int to long. Narrowing requires an explicit cast because it can lose information, as in (int) someLong, which silently discards the high bits rather than failing.
Why does 0.1 plus 0.2 not equal 0.3 in Java?
Because double is binary floating point and neither 0.1 nor 0.2 has an exact binary representation, so the sum is 0.30000000000000004. This is not a Java bug but how IEEE 754 works in every language that uses it. Never compare doubles with ==, and never use them for money.
What should you use for money instead of double?
BigDecimal, constructed from a string rather than a double so you do not inherit the imprecision you are trying to avoid. Write new BigDecimal("0.1"), not new BigDecimal(0.1). It is immutable, so add returns a new value rather than modifying the receiver.
What is the difference between == and equals for objects?
== compares references, asking whether two variables point at the same object. equals compares values, if the class has overridden it to do so. For primitives there is no equals and == compares values directly, which is why the distinction only bites with objects.
What are local, instance and static variables?
A local variable lives inside a method and dies when it returns. An instance variable belongs to one object and exists as long as that object does. A static variable belongs to the class, so one copy is shared by every instance. Local variables must be initialized before use, while the other two get type defaults.
What is the default value of an uninitialized variable?
Fields get type defaults: zero for numbers, false for boolean, null for references. Local variables get nothing at all, and reading one before assignment is a compile error, not a runtime surprise. That difference is itself a common interview question.
What does the var keyword do?
It infers a local variable's type from its initializer, so var names = new ArrayList<String>(); is typed ArrayList<String>. Java remains statically typed; only the writing is shorter. It works for local variables only, not fields, parameters or return types.
What is the difference between prefix and postfix increment?
++i increments then yields the new value; i++ yields the old value then increments. As a standalone statement they are identical, so the difference only matters inside a larger expression. That is exactly where online assessments put them.
What is short circuit evaluation?
&& skips its right side when the left is false, and || skips it when the left is true. This is what makes if (s != null && s.length() > 0) safe. The single character & and | forms always evaluate both sides, which is why swapping them introduces null pointer bugs.
What does integer division do in Java?
Dividing two integers truncates toward zero, so 7 / 2 is 3 and not 3.5. To get a decimal result at least one operand must be floating point, as in 7 / 2.0. Dividing an integer by zero throws ArithmeticException, while dividing a double by zero yields Infinity.
What does the modulus operator return for negative numbers?
The result takes the sign of the left operand, so -7 % 3 is -1 rather than 2. This differs from the mathematical modulo that some other languages implement, and it is a frequent output prediction question.
What is the ternary operator?
A three part conditional expression, condition ? valueIfTrue : valueIfFalse, which produces a value rather than performing an action. Use it for a simple either-or assignment and avoid nesting it, because nested ternaries are harder to read than the if they replaced.
What is the difference between final, finally and finalize?
Three unrelated things with similar names, which is why the question gets asked. final prevents reassignment, overriding or subclassing. finally is the block that runs whether or not an exception was thrown. finalize was a method intended for cleanup before garbage collection, is deprecated for removal, and should never be used.
Control Flow and Loops
Which loop constructs does Java have?
Four: the classic for with counter, condition and update; the enhanced for for iterating a collection or array; while, which tests before each pass; and do while, which tests after. Pick for when you know the count, while when you do not.
What is the difference between while and do while?
while checks the condition first, so its body may never run. do while runs the body once before checking, so it always executes at least once. Menu loops and input validation are the usual reasons to want the second form.
What is the enhanced for loop and what can it not do?
It reads each element in turn, as in for (String name : names), with no index to manage. What it cannot do is give you the index, iterate backwards, or safely remove elements while looping. Needing any of those is the signal to go back to a classic for or an explicit iterator.
What is the difference between break and continue?
break exits the loop entirely; continue skips the rest of the current pass and starts the next one. In a switch, break instead ends that case. Mixing the two up is a reliable way to produce an off by one result.
What is a labeled break?
A way to exit an outer loop from inside a nested one, by naming it: outer: for (...) { for (...) { break outer; } }. It is the rare legitimate alternative to a flag variable. Mention that you know it exists, then say you would usually extract the nested loop into a method and return instead.
When should you use switch instead of if else?
When you are comparing one variable against several constant values. It reads better than a chain of else if and the compiler can check exhaustiveness in the expression form. Use if else when the conditions are ranges or involve different variables.
What is fall through in a switch statement?
When a case has no break, execution continues into the next case. It is occasionally intentional for grouping, but far more often a bug. The arrow form, case 1 -> doSomething();, does not fall through at all, which is the main reason to prefer it.
What is the difference between a switch statement and a switch expression?
A statement performs actions; an expression produces a value you can assign, using -> and, where needed, yield. The expression form must be exhaustive, so the compiler rejects it if you miss a case on an enum. That compile time check is why modern code prefers it.
String label = switch (day) {
case SATURDAY, SUNDAY -> "Weekend";
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
};
How do you iterate over the characters of a string?
Index with charAt inside a classic for, or call toCharArray and use an enhanced for. The first avoids copying the array, which is why it is the usual choice in a coding round.
What is an infinite loop and how do you cause one by accident?
A loop whose condition never becomes false. The classic accidents are forgetting the update statement, updating the wrong variable in a nested loop, and modifying the loop counter inside the body. In an interview, say out loud what makes your loop terminate; it reads as rigor.
Strings for Freshers
Why are Java strings immutable?
Because a String holds its characters in a final array that no method exposes or modifies, so every operation returns a new string. The reasons are safety and sharing: strings can be cached in the pool, used as map keys without their hash changing, and shared between threads with no locking. Say the consequence, not just the fact: a loop that concatenates strings allocates a new object every pass.
What is the string pool?
A region of the heap where the JVM keeps one copy of each distinct string literal. Two identical literals therefore refer to the same object, which is why "abc" == "abc" is true while two strings built at runtime are not. This is the mechanism behind most string comparison puzzles.
What is the difference between a string literal and new String?
A literal is interned in the pool and shared. new String("abc") deliberately creates a separate object on the heap with the same contents, so == against the literal is false while equals is true. There is no good reason to write new String in real code; it exists in interviews to test this understanding.
How should you compare two strings?
With equals for exact content, or equalsIgnoreCase when case does not matter. Never ==, which asks whether they are the same object. If either side might be null, use Objects.equals(a, b) or put the literal first, as in "yes".equals(input).
When should you use StringBuilder instead of plain concatenation?
When you are building a string in a loop. A single expression such as a + b + c is already compiled efficiently, but result += x inside a loop creates a new string on every pass, which turns linear work into quadratic. StringBuilder appends into one growable buffer instead.
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(part).append(",");
}
String result = sb.toString();
What is the difference between StringBuilder and StringBuffer?
Both are mutable character buffers with the same API. StringBuffer synchronizes its methods and StringBuilder does not, so StringBuilder is faster and is the right default. Choose StringBuffer only when one buffer is genuinely shared across threads, which is rare, because the usual answer is to give each thread its own.
What does the intern method do?
It returns the pooled instance for a string's contents, adding it to the pool if absent. So new String("abc").intern() == "abc" is true. It appears in interviews to confirm you understand the pool rather than because anyone calls it.
How do you reverse a string?
The one line answer is new StringBuilder(s).reverse().toString(). Interviewers often then ask for it without library help, so know the two pointer swap on a char array as well. Say the library version first, then offer the manual one.
How do you check whether two strings are anagrams?
Sort both character arrays and compare, which is simple and runs in n log n. The faster answer is a 26 element count array, incrementing for one string and decrementing for the other, then checking every slot is zero. Mention that the second assumes lowercase ASCII only.
What does String.format do?
It builds a string from a template and arguments, as in String.format("%s is %d", name, age). The common specifiers are %s for any object, %d for integers, %f for decimals and %n for a platform newline. It is the readable alternative to long concatenation chains.
What is a text block?
A multi line string literal delimited by three double quotes, which preserves line breaks and strips the common leading whitespace. It removes the escaping noise from embedded JSON, SQL and HTML. It has been a standard feature since Java 15, so it is safe to mention.
What does split do and what is the common mistake with it?
split breaks a string on a regular expression, not a plain character. So splitting on "." matches every character and returns an empty array, and you need "\\." instead. That surprise is the reason the question exists.
What is the difference between length and length()?
length is a field on arrays; length() is a method on String. Collections use neither and expose size(). Three names for one idea, which is precisely why it gets asked.
Arrays
How do you declare and initialize an array?
int[] a = new int[5];
int[] b = {1, 2, 3};
int[][] grid = new int[3][4];
Prefer int[] a over int a[], because the type reads as "array of int". The size is fixed at creation and cannot change afterwards.
What values does a newly created array hold?
Type defaults, so an int[] is full of zeros, a boolean[] of false, and any object array of nulls. That last one matters: a new String[3] contains three nulls, not three empty strings, so iterating it and calling a method throws NullPointerException.
How do you get the number of elements in an array?
The length field, with no parentheses, as in a.length. For a two dimensional array, grid.length is the number of rows and grid[0].length the number of columns in the first row. Rows can differ in length, which is what a jagged array means.
What causes ArrayIndexOutOfBoundsException?
Reading or writing an index below zero or at least length. The classic cause is a loop written with <= instead of <, because valid indexes run from 0 to length - 1. It is a runtime exception, so the compiler will not warn you.
Can you change the size of an array after creating it?
No. You create a larger array and copy the contents, which is what Arrays.copyOf does for you. Needing to resize repeatedly is the signal to use an ArrayList, which does exactly this growth internally.
How do you copy an array?
Arrays.copyOf for a full or resized copy, Arrays.copyOfRange for a slice, or System.arraycopy for the low level version. Assigning one array variable to another copies only the reference, so both names then refer to the same array. For object arrays all of these are shallow copies.
How do you sort and search an array?
Arrays.sort(a) sorts in place, ascending. Arrays.binarySearch(a, key) then finds a value, but only gives a correct result on an already sorted array. For descending order on an object array, pass a comparator, because Arrays.sort has no comparator overload for primitives.
What is the difference between an array and an ArrayList?
An array has a fixed size, can hold primitives, and uses length and bracket indexing. An ArrayList grows on demand, holds objects only, and uses size(), get and add. Arrays are marginally faster and more memory efficient; ArrayList is what you want nearly every time in application code.
How do you print the contents of an array?
Arrays.toString(a) for one dimension and Arrays.deepToString(grid) for nested arrays. Passing the array straight to println prints the type and hash code instead of the contents, which is a frequent source of confusion for beginners.
How do you convert between an array and a list?
Arrays.asList(a) gives a fixed size list backed by the array, so add on it throws UnsupportedOperationException. For a real list, wrap it: new ArrayList<>(Arrays.asList(a)). Going the other way, list.toArray(new String[0]).
Methods and Constructors
What is a method signature?
The method name plus its parameter types, in order. The return type is not part of it, which is why you cannot overload two methods that differ only by return type. Access modifiers and parameter names are not part of it either.
Is Java pass by value or pass by reference?
Always pass by value. For a primitive the value is the number, so changes inside the method are invisible outside. For an object the value is the reference, so the method can modify the object the reference points to but cannot make the caller's variable point somewhere else. State it in exactly that two part form, because "pass by reference for objects" is the answer interviewers are listening for and marking wrong.
void rename(StringBuilder sb) {
sb.append(" changed"); // caller sees this
sb = new StringBuilder("new"); // caller does not see this
}
What is a varargs parameter?
A parameter that accepts any number of arguments, written int... numbers and received as an array. It must be the last parameter, and a method can have only one. It is why String.format takes an open ended argument list.
What does a constructor do and when is it called?
It initializes a new object, running once when new is used. It has the same name as the class, declares no return type, and cannot be called again on an existing object. If you write none, the compiler supplies a no argument constructor.
What happens to the default constructor when you write your own?
You lose it. The compiler only inserts a no argument constructor when the class declares none, so adding a constructor that takes arguments makes new MyClass() stop compiling. Add the no argument one back explicitly if you still need it.
Can a constructor be private?
Yes, and it is how you prevent outside code from instantiating a class. Utility classes with only static methods use it, and so do classes that force creation through a static factory method. The class can still construct instances of itself internally.
What is constructor chaining?
One constructor calling another, with this(...) for another constructor in the same class or super(...) for the parent's. The call must be the first statement. It keeps initialization logic in one place instead of duplicated across overloads.
What is the difference between this and super?
this refers to the current object, used to disambiguate a field from a parameter of the same name or to chain constructors. super refers to the parent class, used to call an overridden method or the parent constructor. Both are unavailable in a static context, because there is no current object there.
Can a method be both static and abstract?
No. abstract means subclasses must provide an implementation, which relies on overriding, and static methods are not overridden because they are resolved by the compiler against the declared type. The combination is a compile error.
What is recursion and what does every recursive method need?
A method calling itself on a smaller version of the problem. It needs a base case that returns without recursing, and each call must move toward that base case. Without both you get StackOverflowError, which is the expected answer to the follow up question.
When is a static method the right choice?
When the method does not read or write instance state, such as a pure calculation or a factory method. It then belongs to the class rather than to any object. Making everything static to avoid creating objects is an anti pattern, because it removes your ability to substitute an implementation in tests.
Can a static method access instance variables?
Not directly, because there is no particular object to read them from. It can access them through a reference passed in or created inside the method. An instance method, by contrast, can freely access static members.
OOP for Freshers
These answers stay at the depth a fresher is expected to give: a definition, one example, one consequence. The deeper treatment of dispatch rules, SOLID, equality contracts and sealed hierarchies lives in Java OOP Interview Questions.
What is object oriented programming?
Organizing a program as objects that hold their own data and the operations on it, rather than as procedures acting on shared data. The practical payoff is that each object can change internally without the rest of the program caring. Java supports it through classes, inheritance, interfaces and polymorphism.
What are the four pillars of OOP?
Encapsulation, abstraction, inheritance and polymorphism. The trap is reciting them as a list; interviewers almost always follow up with "give me an example of one from your project", so have a real example ready for each before you name them.
How do you explain encapsulation with one example?
Keeping data private and exposing only controlled operations. A BankAccount with a private balance and a deposit method that rejects negative amounts cannot be put into an invalid state from outside. Without encapsulation any code could set the balance directly and the validation would be unenforceable.
How do you explain abstraction with one example?
Exposing what something does while hiding how. You call list.add(item) without knowing whether the backing store is an array or a linked structure, and that freedom is what lets the implementation change. In code it is expressed through interfaces and abstract classes.
What is the practical difference between abstraction and encapsulation?
Abstraction is about designing the interface, deciding what to expose. Encapsulation is about enforcing it, keeping the internals unreachable. They are frequently confused because good code does both at once, so answer with the two verbs: abstraction hides complexity, encapsulation hides data.
How do you explain inheritance with one example?
A class acquiring the fields and methods of another with extends, so SavingsAccount extends Account gets the balance handling and adds interest. It expresses an is-a relationship. Say that you would reach for composition first, because that is what an interviewer wants to hear next anyway.
How do you explain polymorphism with one example?
One reference type behaving differently depending on the actual object. A List<String> list variable can hold an ArrayList or a LinkedList, and list.add runs that class's implementation. The caller is written once against the interface and works with any implementation.
What are compile time and runtime polymorphism?
Compile time polymorphism is method overloading, resolved by the compiler from the argument types. Runtime polymorphism is method overriding, resolved by the JVM from the object's actual class. The second is the one that matters for design; the first is really just convenient naming.
What is method overloading?
Several methods in a class sharing a name but differing in parameter types, count or order. The compiler picks one from the arguments at the call site. Differing only by return type is not overloading and does not compile.
What is method overriding?
A subclass replacing a parent method's implementation with the same signature. The JVM calls the subclass version even through a parent typed reference, which is what makes polymorphism work. Always write @Override, so a typo in the name becomes a compile error instead of a silent new method.
What are the rules for overriding a method?
Same name and parameter types; return type the same or a subtype; access the same or wider, never narrower; and no broader checked exceptions. Private, static and final methods cannot be overridden. Those constraints exist so that code holding a parent reference cannot be surprised by the subclass.
What is a getter and a setter, and why not make the field public?
Methods that read and write a private field. The reason to prefer them is that a method can validate, convert, log or later be reimplemented, while a public field offers no such hook and becomes part of your API permanently. Worth adding that a field needing no validation and never changing is better made final than wrapped in a setter.
What is the Object class?
The implicit superclass of every class in Java, which is why any object can be assigned to an Object reference. It provides toString, equals, hashCode, getClass and the thread notification methods. The first three are the ones you are expected to know how to override.
Why should you override toString?
Because the default prints the class name and a hash code, which tells you nothing in a log or a debugger. Overriding it to show the meaningful fields is a small change that pays off every time something goes wrong. Records generate a sensible one for you.
How do you explain a class versus an object in an interview?
A class is the definition; an object is one instance of it created with new, with its own copy of the instance fields. One class, many objects. A fresher answer that uses the blueprint and house analogy is fine, as long as you can then name the fields of an actual object you wrote.
Inheritance and Interfaces, the Beginner View
Does Java support multiple inheritance?
Not for classes, so a class has exactly one direct superclass. A class may implement many interfaces, which gives you multiple inheritance of type and, since default methods arrived, of behavior too. The single class restriction avoids the ambiguity where two parents provide the same field.
Why does Java refuse to let a class extend two classes?
It is the ambiguity when a class inherits the same member from two parents by different paths. Java sidesteps it for state by allowing only one superclass. Where two interfaces supply the same default method, the compiler refuses to guess and forces you to override it and pick, with Interface.super.method().
What is an interface?
A contract listing methods a class promises to provide. Its methods are implicitly public and abstract, its fields implicitly public static final. You program against the interface so that the implementation can be swapped without touching the calling code.
Can an interface contain method bodies?
Yes, in three forms since Java 8. default methods give an implementation that implementors inherit, which is how new methods were added to existing interfaces without breaking every class. static methods belong to the interface itself. private methods, added in Java 9, let default methods share code.
Why were default methods added to Java?
To let an interface gain a method without breaking the classes that already implement it. Adding stream() to Collection would otherwise have broken every collection class ever written. That is the real motivation, and it is a better answer than "to allow multiple inheritance".
When do you choose an abstract class over an interface?
Choose an abstract class when subclasses genuinely share state or constructor logic, since only a class can declare instance fields and constructors. Choose an interface in nearly every other case, especially when a type needs several unrelated capabilities. The modern default is the interface, with the abstract class as the exception.
Why does an abstract class have a constructor if you cannot instantiate it?
Yes, and it runs when a concrete subclass is instantiated, via super. You cannot call new on the abstract class itself, but its constructor still exists to initialize the fields subclasses inherit. This is exactly the capability an interface lacks.
Can an abstract class have no abstract methods?
Yes. abstract on the class only means it cannot be instantiated directly. A class with full implementations but marked abstract is a legitimate way to say that it is a base to extend rather than something to use on its own.
What does the final keyword do in each place it can appear?
On a variable it prevents reassignment, though the object it points to can still change internally. On a method it prevents overriding. On a class it prevents subclassing, which is why String is final. One keyword, three distinct meanings, which is why the question is worth preparing.
When do you need a cast between a parent and a child type?
Upcasting is assigning a subclass reference to a parent type, which is always safe and implicit. Downcasting is the reverse, requires an explicit cast, and throws ClassCastException if the object is not actually that type. Guard a downcast with instanceof, or restructure so you do not need one.
What does instanceof do, and what is pattern matching for instanceof?
It tests whether an object is of a given type, returning false for null. Modern Java lets you bind the result in the same expression, so if (o instanceof String s) gives you a typed s inside the block with no separate cast. Use that form; the old test-then-cast pair is now redundant.
What is a marker interface?
An interface with no methods, used purely to tag a class so that other code can check for it, such as Serializable and Cloneable. Annotations have largely replaced the technique. Knowing the term is enough at fresher level.
What happens if a class does not implement every interface method?
It must be declared abstract, otherwise it will not compile. The unimplemented methods remain abstract and a further subclass has to supply them. This is the compiler enforcing the contract rather than letting a half built type exist.
Exception Handling Basics
What is an exception?
An object representing something that went wrong, thrown at the point of failure and handled somewhere up the call stack. It separates error handling from normal logic, instead of returning error codes that callers can ignore. Everything throwable descends from Throwable.
What is the difference between an Error and an Exception?
Both extend Throwable. An Exception is a condition your program could reasonably handle, such as a missing file. An Error signals a problem with the environment itself, such as OutOfMemoryError or StackOverflowError, and should not be caught. The distinction is about whether recovery is realistic.
What is the difference between checked and unchecked exceptions?
Checked exceptions extend Exception and the compiler forces you to either catch them or declare them with throws. Unchecked exceptions extend RuntimeException and carry no such requirement. Use checked for conditions a caller can act on, unchecked for programming mistakes such as a null argument.
| Exception | Kind | Usual cause |
|---|---|---|
| NullPointerException | Unchecked | Using a reference that is null |
| ArrayIndexOutOfBoundsException | Unchecked | Loop condition uses <= instead of < |
| NumberFormatException | Unchecked | Integer.parseInt on non numeric text |
| ArithmeticException | Unchecked | Integer division by zero |
| ClassCastException | Unchecked | Downcasting to the wrong type |
| IOException | Checked | File or network operation failed |
| SQLException | Checked | Database operation failed |
What does the finally block do?
It runs whether or not an exception was thrown, and even when the try or catch block returns, which makes it the place for cleanup. The exceptions are System.exit and the JVM being killed. Never return from a finally block, because it discards the exception that was on its way out.
What is try with resources and why prefer it?
A form that declares resources in the try parentheses and closes them automatically in reverse order, for anything implementing AutoCloseable. It replaces a nested finally that people routinely got wrong. It also handles the case where closing itself throws, attaching that as a suppressed exception rather than losing the original.
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
return reader.readLine();
}
How do you keep throw and throws straight?
throw is a statement that raises an exception now: throw new IllegalArgumentException("negative"). throws is part of a method declaration announcing what it may raise. One letter apart, so say both out loud when you answer to show you are not confusing them.
Can you catch several exception types in one block?
Yes, with the multi catch form catch (IOException | SQLException e), where the variable is effectively final. Use it when the handling is genuinely identical. Catch order matters in separate blocks: a subclass must be caught before its superclass or the code will not compile.
What is wrong with catching Exception?
It swallows everything, including the programming errors you wanted to see, such as NullPointerException. An empty catch block is worse, because the failure then disappears entirely. Catch the narrowest type you can actually handle, and if you must catch broadly, log with the stack trace and rethrow.
What is NullPointerException and how do you avoid it?
It is thrown when you use a reference that is null, usually by calling a method on it. Avoid it by not returning null from your own methods, preferring an empty collection or an Optional, validating arguments at the boundary, and putting the literal first in comparisons. Modern JVMs print a helpful message naming the exact expression that was null, so read it before guessing.
How do you read a stack trace?
Start at the top line for the exception type and message, then read down for the first frame in your own package, because that is usually where the problem is rather than inside the library. Look for Caused by sections further down, where the root cause often sits. Being able to describe this is a disproportionately strong signal at fresher level.
How do you write your own exception class?
Extend RuntimeException for an unchecked one or Exception for a checked one, and provide constructors that pass the message and the cause to super. Keeping the cause matters, because dropping it is how teams end up with stack traces that point nowhere.
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause);
}
}
What happens if an exception is never caught?
It propagates up the call stack, and if nothing handles it the thread terminates and the JVM prints the stack trace. For the main thread that ends the program. In a server application a framework usually catches it at the request boundary and turns it into an error response.
Collections a Fresher Needs
This section covers only what gets asked at entry level. Internal resizing, load factors, hashCode distribution and the concurrent collections are in Java Collections Interview Questions.
What does the Collections Framework give you?
A set of interfaces and implementations for storing groups of objects, with shared algorithms in Collections and Arrays. The value is that you code against List or Map and can change the implementation underneath. It also means you are not writing your own data structures.
What are the main collection interfaces?
Collection at the root, with List for ordered sequences allowing duplicates, Set for unique elements, and Queue for ordered processing. Map sits outside Collection because it stores key to value pairs rather than single elements. That last point is a frequent catch question.
When do you use a List, a Set and a Map?
A List when order matters and duplicates are allowed, such as a sequence of events. A Set when you need uniqueness, such as tags. A Map when you look things up by a key, such as user ID to user. Picking the right one from the requirement is more of what gets tested than knowing the internals.
What is the difference between ArrayList and LinkedList?
ArrayList is backed by an array, so indexed access is constant time and inserting in the middle shifts elements. LinkedList is a doubly linked list, so inserting at a known position is cheap but reaching index n means walking n links. Use ArrayList unless you have measured a reason not to, which in practice is almost always.
What is the difference between HashSet and TreeSet?
HashSet uses hashing, gives no ordering, and offers constant time operations. TreeSet keeps elements sorted and offers log time operations, requiring elements to be comparable or a comparator to be supplied. LinkedHashSet is the middle option, preserving insertion order.
What is the difference between HashMap and Hashtable?
HashMap allows one null key and null values, is not synchronized, and is what you should use. Hashtable synchronizes every method, allows no nulls, and is a legacy class. When thread safety is genuinely needed the answer is ConcurrentHashMap, not Hashtable.
How do you iterate over a Map?
Loop over entrySet() when you need both key and value, which avoids a second lookup per entry. Use keySet() or values() when you need only one side. The compact form is map.forEach((key, value) -> ...).
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
What are generics and what problem do they solve?
Type parameters that let a class or method work with a type supplied by the caller, as in List<String>. They move type errors from runtime to compile time and remove the casting that collections needed before Java 5. Without them, taking an Integer out of a list of strings failed only when the program ran.
What is the diamond operator?
The empty angle brackets in List<String> names = new ArrayList<>();, which tell the compiler to infer the type argument from the declaration. It removes the repetition of naming the type twice. Nothing changes at runtime.
Why must equals and hashCode be overridden together?
Because hash based collections use hashCode to pick a bucket and equals to compare within it. Override only equals and two equal objects can land in different buckets, so a HashSet will hold apparent duplicates and a HashMap lookup will miss. The contract is that equal objects must return the same hash code.
What causes ConcurrentModificationException?
Structurally modifying a collection while iterating it, typically calling remove inside an enhanced for loop. Despite the name it usually has nothing to do with threads. Use iterator.remove(), or removeIf, or collect what you want to drop and remove it after the loop.
What is the difference between Comparable and Comparator?
Comparable is implemented by the class itself, defining its one natural ordering through compareTo. Comparator is a separate object defining an ordering externally, so you can have many and sort a class you do not own. Use Comparator.comparing(Person::getName) rather than writing the comparison by hand.
What is an iterator?
An object that walks a collection one element at a time through hasNext and next, and which the enhanced for loop uses behind the scenes. Its advantage is remove, which safely deletes the current element during iteration. Explaining that the enhanced for compiles down to an iterator is a good sign at fresher level.
What is the difference between Collection and Collections?
Collection is the root interface of the framework. Collections is a utility class of static helper methods such as sort, reverse, unmodifiableList and emptyList. A one letter difference that gets asked precisely because it is easy to confuse.
Modern Java a Fresher Should Recognize
You are not expected to be fluent here. You are expected to recognize these features, say what problem each solves, and not look blank. For working depth, see Java 8 Interview Questions and Java Streams and Lambdas Interview Questions.
What is a lambda expression?
A compact way to write a function you can pass as an argument, as in names.forEach(n -> System.out.println(n)). It implements a functional interface without the ceremony of an anonymous class. It makes behavior a parameter, which is the shift that drove most of the Java 8 library changes.
What makes an interface a functional interface?
An interface with exactly one abstract method, which is what a lambda can be assigned to. Runnable, Comparator, Predicate and Function are examples. The @FunctionalInterface annotation makes the compiler enforce the single method rule.
What is a method reference?
Shorthand for a lambda that only calls an existing method, written String::toUpperCase instead of s -> s.toUpperCase(). The four forms are static, bound instance, unbound instance, and constructor with new. Use it when the lambda body adds nothing.
What is the Stream API in one sentence?
A way to describe a pipeline of operations over a sequence of elements, such as filter then map then collect, instead of writing the loop yourself. Streams do not store data and do not modify the source. Nothing runs until a terminal operation such as collect or forEach is called.
List<String> result = names.stream()
.filter(n -> n.length() > 3)
.map(String::toUpperCase)
.toList();
Which stream operations actually do the work?
Intermediate operations such as filter and map return another stream and are lazy, building up the pipeline without doing work. A terminal operation such as collect, toList, count or forEach triggers execution and ends the stream. A stream cannot be reused after its terminal operation.
What is Optional and when should you use it?
A container that either holds a value or is empty, used as a return type to say that absence is a normal outcome. Read it with orElse, orElseThrow or map, not with get, which throws when empty. Use it for return values, not for fields or parameters.
What is a record?
A concise declaration for an immutable data carrier: record Point(int x, int y) {} gives you final fields, a constructor, accessors, equals, hashCode and toString. Use it for DTOs and value objects. It cannot extend another class, because that would conflict with its generated equality.
What are the forEach and removeIf methods?
Default methods added to the collection interfaces so you can pass behavior instead of writing a loop. list.forEach(System.out::println) prints each element and list.removeIf(s -> s.isEmpty()) deletes matches safely during iteration. They are the easiest modern features to actually use in a coding round.
What changed about garbage collection in recent Java versions?
The practical change worth knowing is that G1 became the default collector in all environments in Java 27, where previously a small or single processor machine would have defaulted to the serial collector. For a fresher the expected depth is only that the JVM reclaims unreachable objects automatically, that you cannot force it, and that System.gc() is a suggestion the JVM may ignore. The detail is in JVM Interview Questions.
Do you need to know streams for a fresher interview?
Know enough to recognize a pipeline, explain filter and map, and write a simple one if asked. You will not be expected to discuss collectors in depth or parallel streams. If an interviewer offers you the choice in a coding round, a clear loop is a perfectly good answer and is often easier to debug out loud.
Predict the Output Questions
Online assessments lean on these heavily, because they separate candidates who understand the rules from candidates who have read about them. Cover the code, decide your answer, then check.
What does this string comparison print?
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
true, false, true. The two literals are the same pooled object, so == is true. new String forces a separate object, so == is false while equals still compares contents.
What does this Integer comparison print?
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
true then false. Autoboxing caches Integer values from -128 to 127, so the first pair is one shared object and the second pair is two. This is the single most common output trap in fresher assessments, and the lesson is to compare wrappers with equals.
What is the value of i after this?
int i = 5;
i = i++;
System.out.println(i);
5. The postfix increment yields the old value 5, which is then assigned back over the incremented 6. The increment happens and is immediately overwritten.
What does this char and string concatenation print?
System.out.println('a' + 'b');
System.out.println("" + 'a' + 'b');
System.out.println(1 + 2 + "3");
System.out.println("1" + 2 + 3);
195, ab, 33, 123. Two chars promote to int and add numerically. Once a string is involved, + concatenates, and it evaluates left to right, which is why the third line adds before concatenating and the fourth does not.
What does this method return and what does it print?
static int test() {
try {
return 1;
} finally {
System.out.println("finally");
}
}
It prints finally, then returns 1. The return value is computed before the finally block runs, which is why finally cannot change it unless it contains its own return.
What does this arithmetic print?
System.out.println(0.1 + 0.2);
System.out.println(5 / 2);
System.out.println(5 / 2.0);
System.out.println(-7 % 3);
0.30000000000000004, 2, 2.5, -1. Binary floating point cannot represent 0.1 exactly, integer division truncates, one double operand promotes the whole expression, and the remainder takes the sign of the left operand.
What does this array code print?
int[] numbers = {1, 2, 3};
for (int n : numbers) {
n = n * 2;
}
System.out.println(Arrays.toString(numbers));
[1, 2, 3]. The loop variable is a copy of each element, so assigning to it changes nothing in the array. To modify in place you need the index form and numbers[i] = numbers[i] * 2.
What does this string method call print?
String s = "hello";
s.toUpperCase();
System.out.println(s);
hello. Strings are immutable, so toUpperCase returns a new string that the code discards. You need s = s.toUpperCase().
In what order does this run?
class Demo {
static { System.out.println("static block"); }
{ System.out.println("instance block"); }
Demo() { System.out.println("constructor"); }
}
// new Demo(); new Demo();
static block, then instance block, constructor, instance block, constructor. The static block runs once when the class is first loaded. The instance initializer runs before the constructor body on every instantiation.
What does this empty object array print?
String[] names = new String[2];
System.out.println(names.length);
System.out.println(names[0]);
System.out.println(names[0] + "!");
2, null, null!. An object array is filled with nulls, and string concatenation converts a null reference to the text "null" rather than throwing. Calling a method on names[0] would throw instead, which is the distinction being tested.
Does this compile, and if so what does it print?
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
list.remove(1);
System.out.println(list);
It compiles and prints [1, 3]. The remove(int) overload matches first and removes the element at index 1, not the value 1. To remove by value you must box it: list.remove(Integer.valueOf(1)).
What does this unboxing code do?
Integer count = null;
int total = 0;
if (count != null) total += count;
System.out.println(total);
int other = count;
It prints 0, then the last line throws NullPointerException. Assigning a null Integer to an int unboxes it, and unboxing null fails even though the line contains no visible method call.
Fresher Coding Round Problems
These are the problems that actually come up at entry level. Interviewers care less about the optimal solution than about whether you state your approach before typing, handle the empty and single element cases, and can say the time complexity afterwards.
How do you reverse a string without using library methods?
static String reverse(String input) {
char[] chars = input.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left++] = chars[right];
chars[right--] = temp;
}
return new String(chars);
}
Two pointers swapping inward, O(n) time and O(n) space for the array. Mention that new StringBuilder(input).reverse().toString() is what you would write in real code.
How do you check whether a string is a palindrome?
static boolean isPalindrome(String input) {
int left = 0, right = input.length() - 1;
while (left < right) {
if (input.charAt(left++) != input.charAt(right--)) return false;
}
return true;
}
Same two pointer idea without allocating anything, O(n) time and O(1) space. The follow up is usually to ignore case and non letters, which means skipping characters that fail Character.isLetterOrDigit.
How do you write FizzBuzz?
for (int i = 1; i <= 100; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
The only trap is ordering: test the 15 case first, or multiples of fifteen print "Fizz" and never reach the combined branch. It is asked to confirm you can write a loop with conditions at all.
How do you generate the Fibonacci sequence?
static void fibonacci(int count) {
long previous = 0, current = 1;
for (int i = 0; i < count; i++) {
System.out.print(previous + " ");
long next = previous + current;
previous = current;
current = next;
}
}
Iterative, O(n) time and O(1) space. If you offer the recursive version, say immediately that it is O(2^n) because it recomputes the same values, and that memoizing or iterating fixes it. Use long, because an int overflows at the 47th term.
How do you check whether a number is prime?
static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (int i = 3; (long) i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
Checking to the square root rather than to n is the whole point of the question, taking it from O(n) to O(sqrt n). Handling numbers below 2 and skipping even divisors is what separates a careful answer from a nearly correct one.
How do you find the second largest element in an array?
static int secondLargest(int[] a) {
int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : a) {
if (n > largest) { second = largest; largest = n; }
else if (n > second && n != largest) { second = n; }
}
if (second == Integer.MIN_VALUE) throw new IllegalArgumentException("no second largest");
return second;
}
One pass, O(n) time. Sorting and taking the second to last element also works but is O(n log n) and breaks on duplicates. Ask whether duplicates count as distinct before you start, because that is the real question being tested.
How do you count character frequency in a string?
static Map<Character, Integer> frequency(String input) {
Map<Character, Integer> counts = new HashMap<>();
for (char c : input.toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
return counts;
}
O(n) with a map. merge is the clean way to write insert-or-increment; getOrDefault(c, 0) + 1 is the version to use if you would rather not rely on remembering merge. Use a LinkedHashMap if the follow up asks for insertion order.
How do you find the first non repeating character?
static Character firstUnique(String input) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : input.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return null;
}
Two passes, both O(n). The LinkedHashMap is doing real work here: a plain HashMap loses insertion order, so "first" would be meaningless. Say that out loud, because it is the reason the question is asked.
How do you remove duplicates from an array?
static int[] removeDuplicates(int[] a) {
Set<Integer> seen = new LinkedHashSet<>();
for (int n : a) seen.add(n);
return seen.stream().mapToInt(Integer::intValue).toArray();
}
O(n) using a set that preserves order. If the interviewer forbids collections, sort the array and compact it in place with a write pointer, which is O(n log n) but needs no extra structure.
How do you reverse a number and sum its digits?
static int reverseNumber(int n) {
int reversed = 0;
while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
Repeatedly take the last digit with % 10 and drop it with /= 10. Replace the accumulation with sum += n % 10 and you have digit sum, which is the same pattern and a common variant. Mention that reversing a large number can overflow an int.
How do you swap two numbers without a third variable?
a = a + b;
b = a - b;
a = a - b;
Arithmetic swapping, which works but can overflow for large values; the XOR version has the same issue in reverse, failing when both references are the same variable. The answer worth adding is that a temporary variable is clearer and that no real codebase avoids one.
How do you print a pyramid pattern?
for (int row = 1; row <= n; row++) {
for (int space = n - row; space > 0; space--) System.out.print(" ");
for (int star = 1; star <= 2 * row - 1; star++) System.out.print("*");
System.out.println();
}
Pattern questions are pure nested loop control, common in service company tests. The method is always the same: work out the count of each thing as a formula in the row number, here n - row spaces and 2 * row - 1 stars.
How do you write bubble sort and what is its complexity?
static void bubbleSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
boolean swapped = false;
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
O(n^2) worst and average case, O(n) best case with the swapped flag on already sorted input. The - i in the inner bound matters, because the last i elements are already in place. Expect a follow up on which sort you would actually use, where the answer is Arrays.sort.
How do you implement binary search?
static int binarySearch(int[] a, int target) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
O(log n), and it requires a sorted array, which you should state before writing anything. Two details interviewers watch for: low + (high - low) / 2 rather than (low + high) / 2 to avoid overflow, and <= in the loop condition so a single element range is still checked.
Mistakes That Cost Freshers Offers
Comparing strings with ==
It passes in testing because small literals are pooled, then fails on strings read from a file or a request. Use equals always. This is the single most common correctness error in fresher code.
Writing a loop condition with <= on an array
Valid indexes run from 0 to length - 1, so i <= a.length throws on the final pass. Say the bound out loud as you write the loop in an interview; it catches the mistake before the interviewer does.
Removing from a collection inside an enhanced for loop
This throws ConcurrentModificationException, and the name misleads people into looking for a threading problem. Use removeIf or an explicit iterator.
Using double for money
Prices do not add up and totals drift by fractions of a cent, which an interviewer will probe if your project handled payments. BigDecimal built from strings, or integer minor units such as cents.
Overriding equals but not hashCode
The class then behaves correctly in a list and incorrectly in a HashSet or as a HashMap key, which is a bug that surfaces far from its cause. Generate both from your IDE, or use a record.
Catching Exception and doing nothing
An empty catch block deletes the evidence of a failure, so the program continues in a broken state with no trace. Catch the specific type, and if there is genuinely nothing to do, log it with the stack trace.
Reciting a definition you cannot expand
Memorized paragraphs are easy to spot, because the follow up question gets a different register of answer. Prepare one real example for every concept instead of a second paragraph.
Claiming skills your resume cannot support
Listing a framework you used for one tutorial invites ten minutes of questions you cannot answer, and the damage spreads to everything else you claimed. Cut the resume down to what you can defend for two minutes each.
Staying silent during a coding problem
A wrong approach narrated aloud scores better than a correct one produced in total silence, because the interviewer is assessing how you think as much as what you produce. Say your plan, then your assumptions, then write.
Talking About Your Projects
How do you discuss a project when you have no work experience?
Use four sentences: what it does, what you personally built, one technical decision you made, and one thing you would change now. The third and fourth carry the weight, because everyone has a project and almost nobody can name a decision they made within it.
What will the interviewer actually ask about your project?
Expect "why did you choose that", "what was the hardest bug", "how did you test it", and "what would you do differently with more time". None of those require an impressive project. They require that you remember the work honestly.
What if your project was built by following a tutorial?
Say so, then describe what you changed or added afterwards, even if small. "I followed a tutorial for the setup, then added search and rewrote the data layer because the original kept everything in memory" is a credible answer. Presenting tutorial work as original design is the version that ends badly.
What if you used AI tools to write part of your project?
Be straightforward about it, since it is now normal and interviewers mostly care about something else: whether you can explain and defend the code that resulted. The failure mode is being unable to walk through your own repository line by line. Before any interview, read your project code again and make sure you could rewrite any file from scratch.
How do you explain your contribution to a team project?
Name your part specifically and credit the rest without diminishing yourself. "Three of us built it; I owned the authentication and the database schema" is clear and verifiable. Avoid "we" for everything, because the interviewer cannot hire the team.
What makes a project stand out to an interviewer?
That it runs, that it solves a problem you can describe without jargon, and that it contains at least one decision with a trade-off you can discuss. A small working thing beats an ambitious half finished one. A README with setup steps and a screenshot does more than another feature.
Should you bring code to the interview?
Have a public repository link on your resume and know it well enough to navigate from memory. Do not expect to screen share unless invited. The point is that the work is inspectable, which raises the credibility of everything you say about it.
HR and Behavioral Questions for Freshers
Tell me about yourself
Sixty to ninety seconds: where you studied and what you focused on, one project or internship with a concrete detail, what you want to work on next, and why this role. Do not recite your resume chronologically. End on the role, so the conversation moves where you want it to.
Why Java?
Give a real reason rather than "it is widely used". Something you built, something you liked about the static typing or the tooling, or the kind of systems it is used for. The question is checking whether you chose a direction or defaulted into one.
Why should we hire you with no experience?
Answer with evidence of learning speed rather than enthusiasm. Point to something you taught yourself and the result, then say that you are looking for a place to be trained properly. The honest version of this answer is stronger than a confident one, because the interviewer already knows your experience level.
What is your biggest weakness?
Name a real one with the correction already in progress: "I used to start coding before understanding the requirement, so now I write down the inputs and outputs first." Avoid the disguised boast, such as being a perfectionist. Avoid anything disqualifying, such as missing deadlines.
Where do you see yourself in five years?
A direction, not a title. Deep in backend engineering, or moving toward system design, or specialized in a domain. Saying "in your company as a manager" is a worse answer than a plausible technical path.
What is your expected salary as a fresher?
For a campus or batch hire the band is usually fixed, so the honest answer is that you are open to the standard offer for the role. For an off campus role, research the range first and give a range rather than a number. Never give a figure you have not checked, and do not be the first to narrow it if you can avoid it.
Are you willing to work in a technology other than Java?
Say yes if it is true, which it should be at this stage. The question is screening for rigidity, and service companies ask it because allocation is out of your control. You can add that you would like to keep growing in backend work, which is a preference rather than a condition.
How do you explain a low CGPA or an academic gap?
State it briefly, give the reason without a long story, and move to what you did about it. One sentence of explanation and one of evidence. Interviewers mostly want to see that you are not evasive about it.
How do you approach learning something new?
Describe your actual process with one example: what you read, what you built with it, how you knew you had understood it. "I build a small project and break it on purpose" is a good answer because it is specific. Vague answers about being a fast learner carry no information.
Do you have any questions for us?
Always have two ready. Good ones: what does a new joiner work on in the first three months, how is code reviewed here, what does the team use for testing. Asking nothing reads as indifference, and asking only about leave policy reads worse.
A Four Week Preparation Plan
How long does a fresher need to prepare?
Four focused weeks is enough if you already know the language, and the plan below assumes roughly two hours a day. Preparing for months tends to mean rereading notes rather than closing gaps. The test for readiness is whether you can write the coding problems above on paper without checking anything.
| Week | Focus | Daily output |
|---|---|---|
| 1 | Language basics, types, operators, control flow, strings, arrays | Write every example by hand, no IDE autocomplete |
| 2 | OOP, inheritance, interfaces, exceptions | One real example per concept from your own project |
| 3 | Collections, generics, output prediction, coding problems | Two coding problems a day, timed at 20 minutes |
| 4 | Mock interviews, project walkthrough, HR answers | Explain aloud to someone, or record yourself |
How many coding problems should you solve?
Around forty well understood problems beats three hundred skimmed ones. Cover strings, arrays, basic recursion, searching and sorting, and the small number theory problems such as prime and palindrome. Re-solve the ones you got wrong a week later, because that is where the learning actually happens.
Should you use AI assistants while preparing?
Use them to explain a concept you are stuck on, and not to produce solutions you then read and feel you understood. The interview tests recall and reasoning without a tool, so practice has to match those conditions. A reasonable rule is to solve first, then ask for a critique of what you wrote.
How do you practice explaining answers out loud?
Say each answer to a timer, aiming for 30 to 45 seconds, and record a few. You will hear the filler, the memorized phrasing and the places where you trail off. This is the highest return activity in the final week and the one almost nobody does.
What should you do the day before the interview?
Reread your own project code, rehearse your "tell me about yourself", check the logistics, and stop studying new material. Cramming a new topic the night before mostly adds noise to topics you already knew. Sleep matters more than one more concept.
What should you do after the interview?
Write down every question you were asked while you still remember it, and mark the ones you answered badly. That list is the most accurate study guide you will ever get, and fresher processes have enough rounds that you will use it within days.
Related Java Interview Resources
Core Java Interview Questions, the next step up in depth on the same topics, organized by experience level.
Java OOP Interview Questions, the four pillars in full, plus SOLID, dispatch rules, equality contracts, records and sealed types.
Java Collections Interview Questions, internal resizing, hashing, ordering guarantees and the concurrent collections.
Java 8 Interview Questions, lambdas, functional interfaces, Optional and the date and time API in working detail.
Java Streams and Lambdas Interview Questions, collectors, grouping, parallel streams and the pipelines that come up after your first year.
Java Multithreading Interview Questions, threads, synchronization and the executor framework, for when a role asks beyond fresher scope.
Java Developer Interview Questions, the full topic map across experience levels, including design and debugging rounds.
Java Developer Salary Guide, context before the compensation conversation in your HR round.
Frequently Asked Questions
- What do companies actually test in a fresher Java interview?
- Three things, in this order: whether you can write a small correct program, whether you understand what your own code does, and whether you will be straightforward to train. Nobody expects production experience. They are checking that the fundamentals are real rather than memorized, because a fresher who understands twenty concepts properly is easier to grow than one who has skimmed two hundred.
- What are the rounds in a typical fresher hiring process?
- Most companies run some subset of the following. Smaller companies compress it into two rounds, while large service companies run all of them across several weeks.
- How is a service company interview different from a product company interview?
- Service companies hire in large batches, so they lean on standardized online assessments and ask broad definitional questions across many topics. Product companies hire fewer people and weight the coding round far more heavily, often with a data structures problem harder than anything in a service company test. Prepare breadth for the first and problem solving for the second.
- How much Java do you need to know as a fresher?
- The fundamentals on this page, plus the ability to write around forty lines of correct code without an IDE autocompleting for you. You do not need JVM internals, the concurrency utilities, or framework internals. Knowing those areas exist and roughly what they solve is enough at this stage.
- Which Java version should a fresher learn on?
- Java 21 or Java 25, both long term support releases. Java 27 is the newest release, generally available since September 2026, but it is a short support release that almost no company runs in production. Many real codebases are still on Java 17 or Java 21, which is why interviewers rarely ask about anything newer.
- What does LTS mean and why does it matter in an interview?
- LTS stands for long term support. Vendors ship a feature release every six months but designate one every two years for extended support. Java 17, 21 and 25 are LTS releases, and the next is expected to be Java 29 around September 2027, which you can check against the Oracle Java SE support roadmap. It matters because the honest answer to "which version do you use" is an LTS version, and answering "the latest one" signals you have not seen a real codebase.
- Do freshers get asked about Spring or Hibernate?
- Sometimes, usually as a single awareness question rather than a deep one. If your resume lists Spring Boot, expect to be asked what dependency injection means and to walk through one endpoint you built, and skim Spring Boot Interview Questions for the handful you are likely to get. The same applies to Hibernate if your project used JPA. If your resume lists neither, you will rarely be pushed there. Never list a framework you cannot discuss for two minutes.
- How long should your answers be?
- Aim for 30 to 45 seconds: a one sentence definition, one concrete detail or example, then stop. Stopping is the part freshers get wrong. A short correct answer invites a follow up question, which is how a conversation builds, whereas a three minute monologue hides whether you understood what was asked.