How the examiner runs a Java lab viva
The Java or object-oriented programming lab usually covers classes and constructors, inheritance and interfaces, packages, exception handling, string handling, collections, multithreading, file I/O, a JDBC program and a small GUI with AWT or Swing. At the practical you write and run one program, and then face a five-to-ten-minute viva with your record open. Viva marks are a separate part of the practical marks under most university schemes.
- First, your program: 'why is this method static?', 'why did you catch this exception here?'
- Then the OOP concept behind it: overloading versus overriding, abstract class versus interface.
- Then a what-if: 'what if I remove this constructor?', 'what if I call run instead of start?'
- Then something deeper if you are doing well: string pool, how HashMap stores entries, wait versus sleep.
- Expect at least one question on the main method signature. Explain it word by word.
Talk about your own class
Every answer lands better with one line from your record: 'In my Shape program, area is abstract in Shape and each subclass overrides it.' Examiners remember the student who connects the definition to their code.
Java basics: JVM, data types and strings
What is Java, and what are its main features?
Java is a high-level, class-based, object-oriented language released by Sun Microsystems in 1995 and now maintained by Oracle and the OpenJDK community. Its main features are platform independence through bytecode, automatic garbage collection, strong typing, built-in multithreading, security checks and a large standard library.
Why is Java platform independent?
javac compiles source code into bytecode, not into machine code for one processor. Any machine with a Java Virtual Machine can run that bytecode, so the same class file runs on Windows, Linux or macOS. The JVM itself is platform-specific; the bytecode is not.
The short line examiners like: write once, run anywhere.
What is the difference between JDK, JRE and JVM?
The JVM is the virtual machine that loads, verifies and executes bytecode. The JRE is the JVM plus the core class libraries needed to run programs. The JDK is the full development kit: the runtime plus tools like javac, java, jar, javadoc and the jdb debugger.
What is the JIT compiler?
The just-in-time compiler is part of the JVM. It watches which methods run often and compiles their bytecode into native machine code at run time, so those parts run much faster than if they were interpreted every time.
Explain public static void main(String[] args).
public so the JVM can call it from outside the class; static so it runs without creating an object; void because it returns nothing to the JVM; main is the name the JVM looks for; and String array args holds the command-line arguments passed to the program.
What are the primitive data types in Java?
Eight: byte of 1 byte, short of 2, int of 4, long of 8, float of 4, double of 8, char of 2 bytes because Java uses UTF-16 Unicode, and boolean, which holds only true or false. Unlike C, these sizes are fixed on every platform.
What are wrapper classes and autoboxing?
Wrapper classes such as Integer, Double and Character wrap a primitive in an object, which collections need because they store only objects. Autoboxing is the automatic conversion from int to Integer, and unboxing the reverse, done by the compiler since Java 5.
What is the difference between double-equals and equals?
For objects, the double-equals operator checks whether two references point to the same object. The equals method checks whether the contents are equal, if the class overrides it, as String does. For primitives, double-equals compares the values directly.
Why are strings immutable in Java?
Once a String object is created its content cannot change; any change creates a new object. This makes strings safe to share across threads, allows the string pool to reuse literals, and keeps their hash code stable for use as HashMap keys. It also protects values like file names and URLs.
What is the string constant pool?
A special area in the heap where string literals are stored once and reused. If I write two literals with the same text, both references point to the same pooled object. Creating a string with the new keyword makes a separate object outside the pool.
What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder and StringBuffer are mutable, so appending changes the same object. StringBuffer's methods are synchronized, making it thread-safe but slower; StringBuilder is not synchronized and is faster, so I use it for building strings in a loop in a single thread.
What are the default values of instance variables?
Numeric fields default to zero, char to the null character, boolean to false and object references to null. Local variables get no default value; the compiler gives an error if I use one before assigning it.
What is type casting in Java?
Widening, such as int to long or double, is automatic because no data is lost. Narrowing, such as double to int, must be written explicitly with the type in brackets and may lose the fractional part or overflow. For objects, a downcast to a subclass is checked at run time.
Is Java pass by value or pass by reference?
Always pass by value. For primitives the value is copied. For objects, the value of the reference is copied, so the method can change the object's fields, but reassigning the parameter to a new object does not affect the caller's variable.
OOP in Java: classes, constructors, inheritance and interfaces
What are the four pillars of OOP?
Encapsulation, hiding data inside a class behind methods; inheritance, reusing a parent class in a child class; polymorphism, one interface with many forms, through overloading and overriding; and abstraction, showing only essential features through abstract classes and interfaces.
What is the difference between a class and an object?
A class is a blueprint that defines fields and methods; it takes no memory for data by itself. An object is an instance of a class created with new, with its own copy of instance fields on the heap. Student is a class; a student with roll number 21 is an object.
What is a constructor, and how is it different from a method?
A constructor initialises a new object. It has the same name as the class, no return type, and runs automatically when new is used. A method has a return type, any name, and runs only when called. Constructors are not inherited.
When does Java provide a default constructor?
Only when the class defines no constructor at all. The compiler then adds a no-argument constructor. If I write any constructor with parameters, the default disappears, so new Student with empty brackets fails to compile unless I write a no-argument constructor myself.
What are this and super?
this refers to the current object; I use it to separate a field from a parameter of the same name and to call another constructor of the same class. super refers to the parent class; it calls the parent's constructor or an overridden method. Both constructor calls must be the first statement.
What is constructor chaining?
Calling one constructor from another, either in the same class with this and arguments, or in the parent class with super and arguments. Every constructor implicitly calls super with no arguments if I do not write a call, so the parent part of the object is always built first.
What is the difference between overloading and overriding?
Overloading means methods in the same class with the same name but different parameter lists; it is resolved at compile time. Overriding means a subclass provides its own version of an inherited method with the same signature; it is resolved at run time by the actual object type.
What is dynamic method dispatch?
When a parent-class reference points to a child object and calls an overridden method, the JVM decides at run time which version to run, based on the object, not the reference type. Shape s equals new Circle, then s dot area calls Circle's area. This is run-time polymorphism.
Can static methods be overridden?
No. A static method with the same signature in a subclass hides the parent's method rather than overriding it, and the call is decided by the reference type at compile time. Private methods cannot be overridden either, because they are not visible to the subclass.
What is the difference between an abstract class and an interface?
An abstract class can have constructors, instance fields and both abstract and concrete methods, and a class can extend only one. An interface defines a contract; its fields are public static final, and a class can implement many. Since Java 8 interfaces can also have default and static methods.
Why does Java not support multiple inheritance of classes?
To avoid the diamond problem: if two parent classes had the same method, the child would not know which one to inherit. Java allows a class to implement multiple interfaces instead, and if two default methods clash, the class must override the method and choose.
What does the final keyword do?
A final variable can be assigned only once, so it acts as a constant. A final method cannot be overridden. A final class cannot be extended; String is an example. A final reference cannot point to another object, but the object's fields can still change.
What does static mean in Java?
A static member belongs to the class, not to any object, so all objects share one copy. Static methods can be called with the class name and can access only static members directly. I used a static counter to count how many Student objects were created.
What is a static block?
A block of code marked static inside a class that runs once, when the class is loaded, before main or any object is created. It is used to initialise static variables, such as loading a JDBC driver or a configuration value.
What are the access modifiers in Java?
private is visible only inside the class; default, with no keyword, is visible inside the same package; protected is visible in the package and in subclasses in other packages; public is visible everywhere. I keep fields private and expose them with getters and setters.
What is a package, and why is it used?
A package is a namespace that groups related classes and interfaces, like java dot util. It avoids name clashes, controls access with default visibility and organises code into folders. java dot lang is imported automatically, which is why String needs no import.
What is the Object class?
Object, in java dot lang, is the root of the class hierarchy; every class extends it directly or indirectly. Its methods include equals, hashCode, toString, getClass, clone, and wait, notify and notifyAll for thread communication.
Why should you override hashCode when you override equals?
The contract says equal objects must have equal hash codes. HashMap and HashSet first use hashCode to find the bucket and then equals to compare. If I override only equals, two equal objects may land in different buckets and the set will store duplicates.
Exception handling
What is an exception?
An exception is an event during execution that disrupts the normal flow, such as dividing by zero or opening a missing file. Java represents it as an object of a Throwable subclass, which can be caught and handled so the program does not terminate abruptly.
What is the exception hierarchy?
Throwable is at the top with two branches. Error covers serious JVM problems, like OutOfMemoryError, which programs should not catch. Exception covers conditions a program can handle; its subclass RuntimeException and its children are unchecked, and the other Exception subclasses are checked.
What is the difference between checked and unchecked exceptions?
Checked exceptions, such as IOException and SQLException, are checked at compile time: the method must catch them or declare them with throws. Unchecked exceptions, such as NullPointerException, ArithmeticException and ArrayIndexOutOfBoundsException, are not checked by the compiler and usually signal programming errors.
Does finally always run?
The finally block runs whether or not an exception is thrown and even if the try block returns, so it is used for cleanup like closing files. It does not run if the JVM stops, for example through System dot exit, or if the thread is killed.
What is the difference between throw and throws?
throw is a statement inside a method that actually throws one exception object, such as throw new IllegalArgumentException. throws is part of a method declaration that lists the checked exceptions the method may pass to its caller.
How do you create a custom exception?
I create a class that extends Exception for a checked exception or RuntimeException for an unchecked one, and pass a message to the super constructor. In my bank program, InsufficientBalanceException was thrown when the withdrawal amount exceeded the balance.
What is try-with-resources?
Introduced in Java 7, it declares resources such as a FileReader or a database Connection in brackets after try, and closes them automatically at the end, even on an exception. The resource must implement AutoCloseable. It replaces the close calls in a finally block.
Can one try block have multiple catch blocks?
Yes. They are checked in order, so more specific exceptions must come before more general ones, or the compiler reports unreachable code. Since Java 7 one catch can handle several unrelated exceptions separated by a vertical bar.
Collections and generics
What is the Collections Framework?
A set of interfaces and classes in java dot util for storing and processing groups of objects. The main interfaces are List, Set, Queue and Map, with implementations such as ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap, plus algorithms in the Collections utility class.
What is the difference between Collection and Collections?
Collection is the root interface for lists, sets and queues. Collections is a utility class with static methods that work on collections, such as sort, reverse, max, min and synchronizedList.
What is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array, so getting an element by index is fast, but inserting in the middle shifts elements. LinkedList is a doubly linked list, so inserting or removing at known positions is fast but access by index means walking the list. I use ArrayList by default.
What is the difference between a List and a Set?
A List is ordered by index and allows duplicates. A Set does not allow duplicates. HashSet has no guaranteed order, LinkedHashSet keeps insertion order and TreeSet keeps elements sorted. I used a HashSet to remove duplicate roll numbers.
How does a HashMap store entries?
It keeps an array of buckets. For each key it computes hashCode, maps it to a bucket index, and stores the key-value pair there. Keys with the same index share the bucket in a list, and since Java 8 a large bucket becomes a balanced tree. equals finds the exact key.
What is the difference between HashMap and Hashtable?
Hashtable is a legacy class whose methods are synchronized and which allows no null key or value. HashMap is not synchronized, so it is faster, and allows one null key and many null values. For thread-safe use today, ConcurrentHashMap is preferred over Hashtable.
What is the difference between HashMap and TreeMap?
HashMap gives constant-time get and put on average with no order. TreeMap keeps keys in sorted order using a red-black tree, with logarithmic-time operations, and supports methods like firstKey and headMap. I used TreeMap to print students sorted by roll number.
What is an Iterator, and what is a fail-fast iterator?
An Iterator walks through a collection with hasNext and next, and can safely remove the current element. Iterators of ArrayList and HashMap are fail-fast: if the collection is modified structurally during iteration other than through the iterator, they throw ConcurrentModificationException.
What is the difference between Comparable and Comparator?
Comparable is implemented by the class itself with compareTo and defines its natural order, like sorting students by roll number. Comparator is a separate object with compare, so I can define several orders, by name or by marks, without changing the class.
What are generics, and why use them?
Generics let a class or method work with a type given as a parameter, such as an ArrayList of String. The compiler then checks types, so a wrong type is a compile error and no cast is needed when reading. The type information is erased at run time, called type erasure.
Multithreading
What are the two ways to create a thread?
Extend the Thread class and override run, or implement the Runnable interface and pass the object to a Thread constructor. Implementing Runnable is preferred because the class can still extend another class, and the task is kept separate from the thread.
What is the difference between start and run?
start creates a new thread of execution, and the JVM then calls run on that new thread. Calling run directly just executes it as a normal method on the current thread, so nothing runs in parallel. Calling start twice on the same thread throws IllegalThreadStateException.
What are the states of a thread?
Java defines six states in Thread dot State: NEW before start, RUNNABLE when running or ready, BLOCKED waiting for a monitor lock, WAITING waiting indefinitely, for example in join or wait, TIMED_WAITING in sleep or a timed wait, and TERMINATED after run finishes.
What is synchronisation, and why is it needed?
When several threads update shared data, their steps can interleave and give wrong results, a race condition. The synchronized keyword on a method or block lets only one thread hold the object's lock at a time. In my bank account program, deposit and withdraw were synchronized.
What is the difference between wait and sleep?
wait is an Object method that must be called inside synchronized code; it releases the lock and waits until notify or notifyAll. sleep is a static Thread method that pauses the current thread for a time without releasing any lock it holds.
How do wait and notify solve the producer-consumer problem?
The producer and consumer synchronize on the shared buffer. When the buffer is full the producer calls wait; when the consumer removes an item it calls notify. When the buffer is empty the consumer waits, and the producer notifies after adding. The wait is placed inside a while loop that rechecks the condition.
What is a deadlock in Java?
Two or more threads each hold a lock and wait for a lock held by the other, so none proceeds. Thread A locks the account, then waits for the log; thread B locks the log, then waits for the account. Acquiring locks in the same fixed order prevents it.
What is thread priority?
Each thread has a priority from 1 to 10, with 5 as normal, set with setPriority. It is only a hint to the scheduler, and the actual effect depends on the operating system, so programs should never rely on priority for correctness.
What does the volatile keyword do?
It makes every read of the variable come from main memory and every write go there, so a change by one thread is visible to others. It does not make compound actions such as count plus plus atomic; for those I need synchronized or an AtomicInteger.
Memory, JDBC, GUI and modern Java
What is the difference between stack and heap memory in Java?
Each thread has its own stack holding method frames, local variables and references; it is freed automatically when a method returns. Objects and their instance fields live on the heap, shared by all threads, and are reclaimed by the garbage collector.
What is garbage collection?
The JVM automatically frees heap memory used by objects that are no longer reachable from any live reference. An object becomes eligible when, for example, its reference is set to null or goes out of scope. System dot gc only requests a collection; it does not force one.
Should we use the finalize method?
No. finalize was meant to run before an object is collected, but there is no guarantee when or whether it runs. It has been deprecated since Java 9 and is marked for removal. Resources should be closed with try-with-resources instead.
What are the steps to connect to a database using JDBC?
Add the driver jar; get a Connection with DriverManager dot getConnection using the URL, user and password; create a Statement or PreparedStatement; execute the query; read the ResultSet row by row; and close everything, ideally with try-with-resources. Older code also loaded the driver with Class dot forName.
Why is PreparedStatement better than Statement?
A PreparedStatement is precompiled with question-mark parameters that are set separately with methods like setInt and setString. The values are never treated as SQL, which prevents SQL injection, and the same statement can be run many times efficiently.
What is the difference between AWT and Swing?
AWT components are heavyweight: they use the operating system's native widgets, so they look different on each platform. Swing components, in javax dot swing, are lightweight and drawn in Java, so they look the same everywhere and offer more components, like JTable and JTabbedPane.
What is the delegation event model?
A source, such as a button, generates an event object when something happens. Listener objects register with the source, and the source calls the listener's method. For a button, I implement ActionListener, register it with addActionListener and write the code in actionPerformed.
Are applets still used?
No. Browsers dropped support for the Java plug-in years ago, and the Applet API was deprecated in Java 9, marked for removal in Java 17 and removed in JDK 26. If an older syllabus asks for an applet, I can explain its life cycle of init, start, paint, stop and destroy, but new GUIs use Swing or JavaFX.
What is a lambda expression and a functional interface?
A functional interface has exactly one abstract method, such as Runnable or Comparator. A lambda expression, added in Java 8, is a short way to provide that method's body inline, for example a comparator that compares two students by marks, without writing an anonymous class.
What is the Stream API?
Added in Java 8, streams process a collection in a pipeline of operations such as filter, map and collect, without writing explicit loops. A stream does not store data or change the source. I used it to filter students with marks above 75 and collect their names into a list.
What is serialization?
Serialization converts an object into a byte stream so it can be saved to a file or sent over a network; deserialization rebuilds it. The class must implement the Serializable marker interface. Fields marked transient are skipped, which is useful for passwords.
Common mistakes in a Java viva
- Saying Java is pass by reference for objects. It passes the reference by value.
- Saying an interface can never have method bodies. Since Java 8 it can have default and static methods.
- Mixing up overloading and overriding, or saying static methods can be overridden.
- Comparing strings with double-equals in your own program and then explaining equals correctly. Fix the code first.
- Saying finally runs in every possible case. System dot exit stops it.
- Calling run instead of start in the threads program and not noticing that everything runs on one thread.
- Describing applets as current technology. Say the API has been removed from the JDK and name Swing or JavaFX instead.
If you do not know
Offer what your code does instead of the term: 'Sir, I am not sure of the exact name, but this block runs once when the class loads, so I loaded the driver there.' A short honest answer scores better than a confident wrong one.
What the ExamPilot AI examiner checks when you practise
In a CS/IT lab viva session on ExamPilot you name the Java program you wrote, say the bank account with custom exceptions or the student list with collections, and an AI examiner questions you by voice for about ten minutes: a line from your code, the OOP concept behind it, a what-if, a comparison and one deeper question. It interrupts when you ramble and asks 'why' after every 'what'. You can answer in English or Hindi.
Start with the CS/IT lab viva mock. You get a transcript, the questions you fumbled and a tighter version of each answer to say again.
The night before the Java lab exam
- 1
Re-run every program in your record
Read each class and mark every keyword you cannot explain: static, final, abstract, synchronized, throws. Those are the first questions.
- 2
Say the ten basics without looking
JDK, JRE and JVM; the main signature; four pillars; overloading versus overriding; abstract class versus interface; checked versus unchecked; String versus StringBuilder; ArrayList versus LinkedList; HashMap; start versus run.
- 3
Predict two outputs aloud
One dynamic dispatch example with a parent reference and child object, and one try-catch-finally with a return inside try.
- 4
Run one mock viva
Ten minutes with the AI examiner on your program shows which answers come out cleanly and which ones you only recognise when you read them.
If your college also has a Python or C lab, see Python viva questions and C programming viva questions. Java programs often meet databases and networks in the same year: DBMS viva questions and computer network viva questions. For placement technical rounds, pair this page with interview questions and answers for freshers.
Frequently asked questions
- What are the most important Java viva questions?
- JDK versus JRE versus JVM, the main method signature, the four pillars of OOP, overloading versus overriding, abstract class versus interface, constructors and this and super, static and final, checked versus unchecked exceptions, String versus StringBuilder, ArrayList versus LinkedList, HashMap, and creating threads. Before these, expect questions on the exact programs in your record.
- Are Java lab viva questions different from Java interview questions?
- The core is the same, but a lab viva starts from your program and stays close to the syllabus, while placement interviews go deeper into collections internals, the equals and hashCode contract, multithreading and Java 8 features, and add a coding task. The answers on this page cover both; for interviews, add one real example from a project to each answer.
- Do examiners still ask about applets?
- Some older syllabi still list an applet experiment, so an examiner may ask about its life cycle. Answer it, and add that the Applet API was deprecated, then removed from the JDK in version 26, and that browsers no longer run applets, so GUIs today use Swing or JavaFX. That shows you know the current state of the language.
- How long should a Java viva answer be?
- Two or three sentences, about twenty to thirty seconds: the definition, one example from your own program, then stop. If the examiner wants more, they ask a follow-up, and handling that follow-up well is where full viva marks come from. Long answers invite interruptions and usually contain the one mistake the examiner chases.
- How can I practise Java viva questions out loud?
- Reading answers silently does not prepare you for being questioned. On ExamPilot you can run a CS/IT lab viva by voice: name your Java program, and the AI examiner asks about it, tests a what-if on constructors, exceptions or threads, and follows up like an external examiner, then gives a transcript to review. It is free to start, in English or Hindi.
Practise out loud
Practise your Java lab viva out loud
The AI examiner asks about the Java program you wrote, the OOP concept behind it and a what-if on exceptions or threads, and scores correctness, brevity and clarity.
Engineering Viva · CS / IT lab viva
