25 Java Basics and JVM questions with answers for java roles — 11 easy, 10 medium, 4 hard.
About Java Basics and JVM
Start with how Java works: JDK, JRE and JVM, bytecode, data types, operators, control flow and the main method. You also learn JVM memory areas, garbage collection, the JIT compiler and class loading, which interviewers use to judge how deeply you understand what happens when a Java program actually runs.
Sheet progressStart 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.
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.
javac compiles source code into bytecode, not native machine code. Any machine with a compatible JVM can run that same .class file, so the code is written once and run anywhere. The JVM itself is platform specific; there are separate JVM builds for Windows, Linux and macOS, but the bytecode they run is identical.
03
What are the primitive data types in Java and their sizes?
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.
04
What is the difference between == and equals() in Java?
== compares primitive values, or for objects it checks whether two references point to the same object in memory. equals() checks logical equality and can be overridden, as String, Integer and most value classes do. For example, new String("a") == new String("a") is false, but equals() returns true. Always use equals() to compare object content.
05
What is the difference between a static and an instance variable?
A static variable belongs to the class, so there is only one copy shared by all objects, and it is created when the class is loaded. An instance variable belongs to each object and gets a separate copy per instance. A counter of created objects should be static, while a customer's name should be an instance field.
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.
07
What is the difference between final, finally and finalize?
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden and a final class cannot be extended. finally is a block that runs after try-catch whether or not an exception occurs, used for cleanup. finalize() was a method called before garbage collection; it is deprecated for removal and should be replaced with try-with-resources or Cleaner.
08
What does the var keyword do and where can it not be used?
var, added in Java 10, lets the compiler infer the type of a local variable from its initializer, for example var list = new ArrayList<String>(). Java stays statically typed. var cannot be used for fields, method parameters or return types, and it needs an initializer that is not null. Use it when the type is obvious to keep code readable.
09
Write a Java program to check whether a number is prime.
Check divisibility only up to the square root, which makes it O(sqrt n).
public 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;
}
The long cast avoids overflow for large n.
10
Write Java code to reverse an integer without converting it to a string.
Take the last digit with % 10 and build the result, checking for overflow.
public static int reverse(int x) {
long rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0;
return (int) rev;
}
Negative numbers work because % keeps the sign in Java.
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.
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.
13
What is garbage collection and how does the JVM decide an object is garbage?
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.
The JVM first interprets bytecode, then profiles which methods run often. The Just In Time compiler converts these hot methods into optimised native code at runtime. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation and C2 applies aggressive optimisations like inlining and escape analysis. This is why Java apps get faster after a warm-up period.
Autoboxing is automatic conversion between a primitive and its wrapper, such as int to Integer, and unboxing is the reverse. A common pitfall is a NullPointerException when unboxing a null Integer. Another is comparing Integer objects with ==, which works only for cached values from -128 to 127. Boxing inside tight loops also creates extra garbage and slows code.
16
What is a ClassLoader and what is the delegation model?
A ClassLoader loads .class files into the JVM. The main loaders are Bootstrap (core classes), Platform (formerly Extension) and Application (classpath). In the parent delegation model a loader first asks its parent to load a class and only loads it itself if the parent cannot. This prevents user code from replacing core classes like java.lang.String.
17
An application gets StackOverflowError in a recursive method. What do you do?
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.
18
A team member compares two Integer values with == and the check fails only for large numbers. Explain.
Integer.valueOf caches objects for values from -128 to 127, so autoboxed small numbers share the same object and == returns true. Larger values create new Integer objects, so == compares two different references and returns false. The fix is to use equals() or compare unboxed int values. Static analysis tools like SonarQube flag this pattern.
19
Which JVM flags would you set to start a production service with a 4 GB heap, G1 and a heap dump on OOM?
Find the process id with jps or ps, then use jcmd, which is the recommended tool.
jps -l
jcmd <pid> Thread.print > threads.txt
jcmd <pid> GC.heap_dump /tmp/heap.hprof
Older tools jstack and jmap do the same. Take three thread dumps a few seconds apart to spot stuck threads, and analyse heap dumps in Eclipse MAT.
21
Tell me about a time you found and fixed a difficult production bug in a Java application.
Situation: our order service crashed with OutOfMemoryError every few days. Task: find the root cause without long downtime. Action: I enabled heap dumps on OOM, analysed the dump in Eclipse MAT and found a static HashMap used as a cache that was never cleared. I replaced it with a bounded Caffeine cache with expiry and added a heap usage alert. Result: no crashes in six months and memory stayed flat.
22
Compare the G1, ZGC and Parallel garbage collectors.
Parallel GC focuses on throughput and uses multiple threads but stops the application during collection. G1, the default since Java 9, splits the heap into regions and targets a pause time goal, which suits most server apps. ZGC is a low latency collector with pauses typically under a millisecond even on very large heaps, and is generational from Java 21. Choose based on latency versus throughput needs.
23
Your service throws OutOfMemoryError: Java heap space in production. How do you investigate?
First capture evidence: enable -XX:+HeapDumpOnOutOfMemoryError and check GC logs to see if heap grows steadily, which signals a leak, or spikes, which signals a large request. Analyse the heap dump in Eclipse MAT or VisualVM and look at the dominator tree for big retainers like static maps or caches. Fix the leak or bound the cache, then increase -Xmx only if the real workload needs it.
24
Users report the app is slow for the first few minutes after every deployment. Why might this happen?
This is usually JVM warm-up. Code runs in the interpreter until the JIT compiles hot paths, and caches, connection pools and class loading are also cold. Fixes include warm-up traffic before adding the instance to the load balancer, pre-initialising pools, class data sharing (AppCDS) to reduce start time, or newer options like CRaC or GraalVM native image when fast start is critical.
25
GC pauses of two seconds are causing request timeouts. How would you reduce them?
Turn on GC logging with -Xlog:gc* and confirm which collections cause the pauses. Reduce allocation rate by fixing heavy object creation in hot paths. Size the heap correctly and set -Xms equal to -Xmx to avoid resizing. Tune G1 with MaxGCPauseMillis or move to ZGC for sub-millisecond pauses on large heaps. Retest under load before rolling out.
Frequently asked questions
How important is Java Basics and JVM in Java interviews?
Start with how Java works: JDK, JRE and JVM, bytecode, data types, operators, control flow and the main method. You also learn JVM memory areas, garbage collection, the JIT compiler and class loading, which interviewers use to judge how deeply you understand what happens when a Java program actually runs.
How should I use the Java Basics and JVM sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.