Interview questions

Java Viva Questions and Answers: The 12 Worth Knowing

July 3, 2025Updated October 23, 20269 min read
Top 30 Most Common Java Viva Questions You Should Prepare For

Twelve Java viva questions with short, correct answers, the follow-up to expect after each, and the old textbook answers that are now out of date.

Most Java viva questions come back to a small core: how a program gets from source code to running, the object-oriented rules, strings and equality, exceptions and the main collections. The twelve below cover it. Each has a short answer you can say in under a minute and the follow-up to expect, because the second question shows whether you understand the first answer or only remember it. At the end is a list of answers from old lab manuals that no longer match current Java.

How Java runs

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

The JVM runs bytecode. The JRE is the JVM plus the standard libraries a program needs. The JDK is the JRE plus the development tools, such as the javac compiler. javac compiles .java files into .class files of bytecode, which the java launcher runs on a JVM.

Follow-up: "So why is Java platform-independent?" Because the same .class files run on any operating system that has a JVM. As the JVM specification says, the JVM knows nothing of the Java language, only the class file format.

2. Why is `main` declared `public static void main(String[] args)`?

public so the launcher can call it from outside the class, static so it can be called without first creating an object, void because it returns nothing to the launcher, and String[] args to receive command-line arguments. The language specification also accepts String... args.

Follow-up: "Can `main` be non-static?" Since Java 25, yes: JEP 512 lets a class declare a plain void main() with no public, no static and no parameters, and the launcher creates an instance to call it. The classic signature still works, and if both exist the launcher picks the one with the String[] parameter. On an older JDK the answer is no, so say which version you mean.

Object-oriented questions

3. What is the difference between overloading and overriding?

Overloading is several methods in one class with the same name and different parameter lists; the compiler chooses which one to call. Overriding is a subclass method with the same signature as an instance method in its superclass; the object's actual class decides which runs. That is runtime polymorphism, one of the four OOP pillars alongside encapsulation, abstraction and inheritance.

Follow-up: "Can you override a static method?" No. A static method with the same signature in a subclass hides the parent's method: which one runs depends on the class you call it through, not the object.

4. Abstract class or interface?

An abstract class can hold instance fields and protected or private concrete methods, and a class can extend only one. A class can implement any number of interfaces. Use an abstract class to share code and state among closely related classes, and an interface for a capability, such as Comparable, that unrelated classes share.

Follow-up: "Why doesn't Java allow multiple inheritance of classes?" To avoid inheriting the same field from two parents. Interfaces have no instance fields, so implementing several avoids that. If two interfaces supply default methods with the same name, the compiler makes the class resolve the clash.

5. `final`, `finally` and `finalize`: what is the difference?

final on a variable means it is assigned once, on a method that it cannot be overridden, on a class that it cannot be subclassed (String is final). finally runs whenever the try block exits, even through an exception or return, unless the JVM exits first. finalize() was a cleanup hook the garbage collector might call.

Follow-up: "Should you use `finalize`?" No. It has been deprecated since Java 9 and marked for removal by JEP 421 in Java 18. For resources, use try-with-resources; for objects that need cleanup when unreachable, the JEP points to Cleaner.

Strings and equality

6. What is the difference between `==` and `equals()`?

For objects, == checks whether two references point to the same object. equals() checks whether two objects are logically equal; String overrides it to compare characters. Object's default equals() is just ==.

A worked example earns marks here. This one is adapted from the example in the Java language specification (section 3.10.5):

String hello = "Hello", lo = "lo";
System.out.println(hello == "Hello");          // true
System.out.println(hello == ("Hel" + "lo"));   // true
System.out.println(hello == ("Hel" + lo));     // false
System.out.println(hello == ("Hel" + lo).intern()); // true

A weak answer says "line one is true, so == works for strings." A strong answer explains each line: string literals are interned, so every "Hello" in the program is the same object; "Hel" + "lo" is a constant expression joined at compile time, so it is that object too; "Hel" + lo uses a variable, so it is built at run time as a new object; intern() returns the shared copy. Conclusion: always compare strings with equals().

7. Why are strings immutable, and when do you use `StringBuilder`?

A String cannot change once created, so one instance can be shared, which is what makes the literal sharing above possible. It also makes strings safe as HashMap keys and safe to pass between threads. To build a string in a loop, use StringBuilder.

Follow-up: "`StringBuilder` or `StringBuffer`?" StringBuilder has the same API as StringBuffer without synchronization; the documentation recommends it whenever only one thread uses it, as it is faster.

8. If you override `equals()`, why must you override `hashCode()`?

The contract in Object says equal objects must return equal hash codes. Unequal objects may share a hash code. If you override only equals(), two "equal" objects can land in different HashMap buckets, and map.get() will not find a key you know is there.

Exceptions

9. Checked versus unchecked exceptions?

Checked exceptions, such as IOException, must be caught or declared with throws. Unchecked exceptions are RuntimeException, Error and their subclasses, such as NullPointerException; the compiler does not require handling them.

Follow-up: "Which should your own exception be?" Oracle's guideline: checked if the caller can reasonably be expected to recover, unchecked if it cannot.

Collections

10. HashMap, Hashtable and ConcurrentHashMap?

HashMap is not synchronized and allows one null key and null values. Hashtable is synchronized and allows no nulls. ConcurrentHashMap is the thread-safe choice: reads generally do not lock, it allows no nulls, and its iterators never throw ConcurrentModificationException.

Follow-up: "How does `HashMap` work inside?" Keys are hashed to buckets in an array. get and put take constant time on average if the hash spreads keys well. Since Java 8 (JEP 180), a crowded bucket switches from a linked list to a balanced tree, cutting the worst case from O(n) to O(log n) for keys that implement Comparable. When entries exceed 75% of capacity (the default load factor), the table roughly doubles.

Methods and threads

11. Is Java pass-by-value or pass-by-reference?

Always pass-by-value. For objects, the value passed is a copy of the reference. A method can change the object's fields and the caller sees it, but reassigning the parameter to a new object does not change the caller's variable. Drawing it as two arrows pointing to one box makes the point quickly.

12. What does `volatile` do?

It makes every thread see the latest value of a field: a write to a volatile variable happens-before later reads of it.

Follow-up: "Is a volatile counter thread-safe?" No. count++ is three steps (read, add, write), and two threads can interleave them and lose an update. Use AtomicInteger or a synchronized block.

Answers from old notes that are now out of date

  • Old answer — Current answer — Changed in
  • "main must be static." — Required in standard Java up to 24; Java 25 also accepts an instance void main(). — JEP 512, Java 25
  • "Use finalize() for cleanup." — Deprecated for removal; use try-with-resources or Cleaner. — Java 9; JEP 421, Java 18
  • "Interfaces cannot have method bodies." — Interfaces can have default methods with bodies. — JEP 126, Java 8
  • "Class metadata lives in PermGen; tune its size." — PermGen was removed; class metadata now lives in native memory. — JEP 122, Java 8
  • "HashMap's worst case is O(n)." — O(log n) for crowded buckets with comparable keys. — JEP 180, Java 8

A one-week plan

Days 1–2: questions 1–5 out loud, with the follow-ups. Days 3–4: questions 6–10; run the string example and a HashMap with a broken hashCode() so you have seen both fail. Day 5: questions 11–12, then explain every keyword in your own lab programs. Days 6–7: a friend quizzes you in random order. For the data-structures part of a lab exam, see our data structure viva questions; if the viva is part of a placement round, Java coding interview questions and tricky Java interview questions are the next step.

To practise answering aloud, Verve AI's Mock Interview has an AI recruiter ask questions one at a time, from a Software Engineering bank or your own saved questions, then gives you a scored feedback report.

Sources

  • javac compiles .java to .class bytecode; the java launcher runs it on a JVM; same .class files on several operating systems: https://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html
  • JVM knows nothing of the Java language, only the class file format: https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-1.html
  • main must be public, static and void with a String[] or String... parameter (Java SE 21): https://docs.oracle.com/javase/specs/jls/se21/html/jls-12.html#jls-12.1.4
  • Instance main methods in Java 25, launcher prefers the String[] version, no-argument constructor requirement: https://openjdk.org/jeps/512
  • Overriding versus hiding static methods, @Override: https://docs.oracle.com/javase/tutorial/java/IandI/override.html
  • Abstract classes compared with interfaces: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
  • Multiple inheritance of state, implementation and type; default method conflicts: https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
  • Final methods and classes: https://docs.oracle.com/javase/tutorial/java/IandI/final.html
  • finally always runs when try exits unless the JVM exits; try-with-resources: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
  • Finalization deprecated for removal in JDK 18; try-with-resources and Cleaner as alternatives: https://openjdk.org/jeps/421
  • Object.equals default behaviour, hashCode contract, finalize deprecated since 9: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html
  • String literal interning and the == example (adapted) with its output: https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.5
  • Strings are constant and can be shared: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html
  • StringBuilder versus StringBuffer: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/StringBuilder.html
  • Checked versus unchecked exceptions guideline: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
  • HashMap nulls, unsynchronized, constant-time get/put, 0.75 load factor: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html
  • ConcurrentHashMap non-blocking reads, no nulls, weakly consistent iterators: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html
  • HashMap balanced-tree buckets, worst case O(n) to O(log n), JDK 8: https://openjdk.org/jeps/180
  • Pass-by-value for primitives and references, moveCircle example: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
  • volatile guarantees a consistent value across threads: https://docs.oracle.com/javase/specs/jls/se21/html/jls-8.html#jls-8.3.1.4
  • volatile writes happen-before later reads; c++ is not atomic: https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
  • c++ decomposes into three steps that can interleave: https://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html
  • Interface default methods (virtual extension methods) in Java 8: https://openjdk.org/jeps/126
  • PermGen removed in JDK 8; class metadata to native memory, interned strings to the heap: https://openjdk.org/jeps/122
  • Verve AI Mock Interview (AI recruiter, question banks including Software Engineering and custom, report with feedback and scoring): https://docs.vervecopilot.com/features/mock-interview
R

Ryan

CEO of Verve AI

Related reads

Explore Related Interview Guides

Why Sql Create Index Is A Must-know For Acing Your Tech Interview
May 9, 2026Interview prep guide

SQL CREATE INDEX Interview: The 30-Second Answer

Master SQL CREATE INDEX interview answers with a 30-second structure: define the index, show one SQL Server example, and state the write-cost tradeoff.

Read guide
Why Sql Create Table Primary Key Isn't Just About Databases, But Your Interview Success
July 31, 2025Interview prep guide

Why Sql Create Table Primary Key Isn't Just About Databases, But Your Interview Success

Get insights on sql create table primary key with proven strategies and expert tips.

Read guide
Why Sql Cross Join Might Be The Most Misunderstood Operator In Your Sql Toolkit
August 1, 2025Interview prep guide

Why Sql Cross Join Might Be The Most Misunderstood Operator In Your Sql Toolkit

Get insights on sql cross join with proven strategies and expert tips.

Read guide
Why Subarray Sum Equals K Is More Than Just A Coding Problem
July 4, 2025Interview prep guide

Why Subarray Sum Equals K Is More Than Just A Coding Problem

Get insights on subarray sum equals k with proven strategies and expert tips.

Read guide
Why Synonym Deployed Is The Key To Unlocking Powerful Professional Communication
July 16, 2025Interview prep guide

Why Synonym Deployed Is The Key To Unlocking Powerful Professional Communication

Get insights on synonym deployed with proven strategies and expert tips.

Read guide
Why The Antonym For Flexibility Might Be Sabotaging Your Interview Success
July 16, 2025Interview prep guide

Why The Antonym For Flexibility Might Be Sabotaging Your Interview Success

Get insights on antonym for flexibility with proven strategies and expert tips.

Read guide
Why The C Required Keyword Is Essential For Interview Success And Robust Code
August 29, 2025Interview prep guide

Why The C Required Keyword Is Essential For Interview Success And Robust Code

Get insights on c# required keyword with proven strategies and expert tips.

Read guide
Why The Highest Difference Is The Most Critical Factor In Your Interview Performance
July 30, 2025Interview prep guide

Why The Highest Difference Is The Most Critical Factor In Your Interview Performance

Get insights on highest difference with proven strategies and expert tips.

Read guide
Why The Spiral Model Is More Than Just A Software Development Approach For Interviews
July 31, 2025Interview prep guide

Why The Spiral Model Is More Than Just A Software Development Approach For Interviews

Get insights on spiral model with proven strategies and expert tips.

Read guide

Walk into every interview prepared and confident

Get Started For Free

Available on Mac, Windows, browser and mobile