0% found this document useful (0 votes)
2 views24 pages

Java Viva Guide

This document is a preparation guide for a Java oral exam covering key topics such as Java basics, OOP concepts, exception handling, multithreading, file handling, collections, GUI, and JDBC. It includes frequently asked questions, important concepts, and mock viva questions to aid in exam readiness. The guide is structured into units with detailed explanations, examples, and common mistakes to avoid.

Uploaded by

ramdevdhane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Java Viva Guide

This document is a preparation guide for a Java oral exam covering key topics such as Java basics, OOP concepts, exception handling, multithreading, file handling, collections, GUI, and JDBC. It includes frequently asked questions, important concepts, and mock viva questions to aid in exam readiness. The guide is structured into units with detailed explanations, examples, and common mistakes to avoid.

Uploaded by

ramdevdhane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA VIVA

PREPARATION GUIDE
Complete Oral Exam Preparation — Units 1 to 5

Second Year Engineering | External Examiner Edition

Covers: Java Basics • OOP • Exception Handling • Multithreading

File Handling • Collections • GUI (AWT/Swing) • JDBC

■ Very Frequently Asked ■ Important ■■ Tricky ■ Must Know

5 100+ 25 Mock
Units Questions Guaranteed Viva
■ TABLE OF CONTENTS

Unit Topic ~Page

1 Java Basics — Features, JVM, Data Types, Operators, Arrays, Strings 4

2 OOP Concepts — Class, Object, Inheritance, Polymorphism, Interface 8

3 Exception Handling & Multithreading — try-catch, Thread, Sync 14

4 File Handling & Collections — Streams, ArrayList, HashMap 18

5 Advanced Java — AWT, Swing, JDBC, Event Handling 22

— Top 100 Questions + Top 25 Guaranteed + Rapid Fire + Mock Viva 26


UNIT 1

JAVA BASICS
Features • JVM • Data Types • Operators • Arrays • Strings

■ Core Theory Questions

■ Q1. What is Java and what are its main features?


■ Answer: Java is a high-level, object-oriented, platform-independent programming language developed by James
Gosling at Sun Microsystems in 1995. Main features: Simple, Object-Oriented, Platform-Independent, Secure, Robust,
Multithreaded, Distributed, Dynamic.

■ Example: Like Android apps — they run on any Android phone regardless of the hardware brand.

■ Cross-Questions: What do you mean by platform-independent? Is Java fully platform-independent? What is WORA?

■■ Common Mistake: Students say 'Java is fast' — Java is slower than C++ due to JVM overhead.

■ Memory Trick: SIMPLE — S:Simple, O:OOP, P:Platform-indep, L:Loaded(dynamic), E:Everything robust

■ Q2. Explain JVM, JRE, and JDK. What is the difference?


■ Answer: JDK (Java Development Kit) = JRE + Development Tools (compiler, debugger). JRE (Java Runtime
Environment) = JVM + Libraries. JVM (Java Virtual Machine) = Engine that runs bytecode. JDK is for developers, JRE
is for users who just run Java programs.

■ Example: JDK = Full kitchen (cooking + eating). JRE = Kitchen to eat only. JVM = The stove that heats food.

■ Cross-Questions: Can you run a Java program without JDK? Can you compile without JDK? Is JVM platform-independent?

■■ Common Mistake: Saying JVM is platform-independent — JVM itself is platform-specific, but bytecode is
platform-independent.

■ Memory Trick: JDK > JRE > JVM — think Bigger to Smaller container

■ Q3. What is bytecode? How does Java achieve platform independence?


■ Answer: When you compile Java code (.java), the compiler (javac) produces bytecode (.class file). This bytecode is
not machine code — it is an intermediate code. The JVM on any OS reads and executes this bytecode. So the same
.class file runs on Windows, Linux, Mac — Write Once Run Anywhere (WORA).

■ Example: Bytecode is like a universal recipe. Every country's chef (JVM) can read it and cook it locally.

■ Cross-Questions: What is the difference between bytecode and machine code? What does javac do? What does java
command do?

■■ Common Mistake: Confusing bytecode with machine code. Bytecode needs JVM to run; machine code runs directly on
CPU.

■ Memory Trick: Bytecode = Universal Intermediate Language understood by every JVM

■ Q4. What are the primitive data types in Java?


■ Answer: Java has 8 primitive types: byte(1B), short(2B), int(4B), long(8B), float(4B), double(8B), char(2B),
boolean(1b). Default values: int=0, double=0.0, boolean=false, char='\u0000', object=null.

■ Example: int age=20; double price=99.99; boolean isPass=true; char grade='A';

■ Cross-Questions: What is the size of int in Java? Is String a primitive type? What is the default value of int?

■■ Common Mistake: Saying String is primitive — String is a class (reference type) in Java.
■ Memory Trick: Byte Short Int Long Float Double Char Boolean — 'By Sam In London Few Dogs Can Bark'

■ Q5. What is the difference between == and .equals() in Java?


■ Answer: == compares references (memory addresses) for objects, and values for primitives. .equals() compares the
actual content/value of objects. For String comparison always use .equals().

■ Example: String a='hello'; String b='hello'; a==b may be true (string pool) but new String('hello')==new String('hello') is false.
Both .equals() would be true.

■ Cross-Questions: What is string pool? What is intern() method? When is == safe to use?

■■ Common Mistake: Using == to compare strings and getting wrong results.

■ Memory Trick: == is address check, .equals() is content check

■ Q6. What are command line arguments in Java?


■ Answer: Command line arguments are values passed to the main method when running a program from the
terminal. They are stored in the String[] args parameter. Example: java Hello Amit 25 — here args[0]='Amit',
args[1]='25'.

■ Example: Like passing ingredients to a recipe when you start cooking.

■ Cross-Questions: What is the type of args? Can you pass integers directly? What if no arguments are passed?

■■ Common Mistake: Trying to use args[0] without checking if [Link] > 0 — causes ArrayIndexOutOfBoundsException.

■ Memory Trick: args = Arguments Ready to Get Started

■ Q7. What is the difference between String, StringBuilder and StringBuffer?


■ Answer: String is immutable — once created, value cannot change. StringBuilder is mutable, not thread-safe, faster.
StringBuffer is mutable, thread-safe (synchronized), slower. Use String for constants, StringBuilder for single-thread
string operations, StringBuffer in multithreaded code.

■ Example: String like a printed book. StringBuilder like a notebook (fast edits). StringBuffer like a locked notebook
(thread-safe but slower).

■ Cross-Questions: What is string immutability? What happens when you concatenate strings with +? What is intern()?

■■ Common Mistake: Using String in loops for concatenation — creates many objects, use StringBuilder instead.
■ Memory Trick: String=Sealed, Builder=Build fast, Buffer=Buffered(thread-safe)

■■ Q8. What is the output? int x=5; [Link](x++ + ++x);


■ Answer: Output: 12. Explanation: x++ returns 5 (post-increment, x becomes 6), then ++x increments first (x becomes
7), so 5+7=12.

■ Example: Post-increment: use then increment. Pre-increment: increment then use.

■ Cross-Questions: What is x++ vs ++x? What is x after this statement? What about x=5; [Link](++x + x++)?

■■ Common Mistake: Forgetting post-increment uses the old value before incrementing.

■ Memory Trick: POST = use first, THEN increment. PRE = increment FIRST, then use.

■ Arrays & Control Flow

■ Q9. What is an array in Java? How is it different from a normal variable?


■ Answer: An array is a collection of elements of the same data type stored in contiguous memory locations with a
fixed size. A normal variable stores one value; an array stores multiple values accessed by index starting from 0.

■ Example: int[] marks = new int[5]; — stores 5 marks. Like a row of 5 lockers.
■ Cross-Questions: What is the default value of int array elements? What is ArrayIndexOutOfBoundsException? Can array
size change?

■■ Common Mistake: Using index equal to length — last valid index is length-1.

■ Memory Trick: Array = Fixed-size box of same-type items

■ Q10. What is the difference between break and continue?


■ Answer: break — exits the entire loop immediately. continue — skips the current iteration and moves to next
iteration. Both work in for, while, do-while loops.

■ Example: break = leave the classroom. continue = skip one question and move to next.

■ Cross-Questions: What happens if break is inside an if inside a for loop? Can break exit nested loops?

■■ Common Mistake: Thinking continue exits the loop — it only skips that one iteration.

■ Memory Trick: Break=STOP, Continue=SKIP

Data Types Quick Reference

Type Size Default Use Case

int 4 bytes 0 Whole numbers

double 8 bytes 0.0 Decimal numbers

char 2 bytes '\u0000' Single character

boolean 1 bit false true/false

long 8 bytes 0L Large whole numbers

float 4 bytes 0.0f Decimal (less precise)

byte 1 byte 0 Small numbers -128 to 127

String varies null Text (class, not primitive)


UNIT 2

OOP CONCEPTS
Class • Object • Inheritance • Polymorphism • Abstraction • Interface

■ OOP Fundamentals

■ Q11. What is Object-Oriented Programming? Name its 4 pillars.


■ Answer: OOP is a programming paradigm that organizes software around objects rather than functions. The 4 pillars
are: 1) Encapsulation — hiding data. 2) Inheritance — reusing code. 3) Polymorphism — many forms. 4) Abstraction
— hiding complexity.

■ Example: A car — engine details hidden (encapsulation), SUV inherits Car features (inheritance), drive() works differently
for diesel/electric (polymorphism), you just press accelerator without knowing internals (abstraction).

■ Cross-Questions: What is the difference between abstraction and encapsulation? Is Java 100% OOP?

■■ Common Mistake: Students confuse abstraction (hiding complexity) with encapsulation (hiding data).

■ Memory Trick: E-I-P-A: Every Indian Person Achieves (Encapsulation, Inheritance, Polymorphism, Abstraction)

■ Q12. What is the difference between a class and an object?


■ Answer: Class is a blueprint/template — it defines properties and methods but occupies no memory. Object is an
instance of a class — it is the actual entity in memory. One class can create many objects.

■ Example: Class = blueprint of a house. Object = actual house built from that blueprint.

■ Cross-Questions: Can a class exist without an object? How many objects can one class have? What is instantiation?

■■ Common Mistake: Confusing class name with object name in viva.

■ Memory Trick: Class = Blueprint, Object = Real Thing built from blueprint

■ Q13. What is a constructor? How is it different from a method?


■ Answer: Constructor is a special method that is automatically called when an object is created. It has the same
name as the class and no return type (not even void). It is used to initialize object data. Method has a name different
from class, has return type, and is called explicitly.

■ Example: Constructor = room setup before guests arrive. Method = activities guests do after arriving.
■ Cross-Questions: What is a default constructor? What is constructor overloading? Can a constructor be private?

■■ Common Mistake: Writing void before constructor name — constructors have NO return type.

■ Memory Trick: Constructor = CLASS name, no return type, auto-called at birth of object

■ Q14. Explain the this keyword in Java.


■ Answer: this refers to the current object of the class. Uses: 1) Distinguish instance variable from local variable with
same name. 2) Call another constructor of same class — this(). 3) Pass current object as argument. 4) Return current
object from method.

■ Example: [Link] = name — left name is instance variable, right name is parameter.

■ Cross-Questions: Can this be used in static method? What is this() constructor call? Can this be null?

■■ Common Mistake: Using this in static methods — static methods have no object context, this is not allowed.

■ Memory Trick: this = 'I am talking about my own properties'


■ Q15. What is inheritance? What are its types in Java?
■ Answer: Inheritance allows a child class to acquire properties and methods of a parent class using the extends
keyword. Types supported: Single (A extends B), Multilevel (A extends B, B extends C), Hierarchical (B and C extend
A). Multiple inheritance with classes is NOT supported in Java to avoid diamond problem. It is achieved through
interfaces.

■ Example: Child inherits mother's eye color and father's height — but you can't have two direct parents in Java classes.

■ Cross-Questions: Why is multiple inheritance not supported in Java? What is diamond problem? What is the super
keyword?

■■ Common Mistake: Saying Java supports multiple inheritance for classes — it does NOT (only for interfaces).

■ Memory Trick: Java extends ONLY ONE class but can implement MULTIPLE interfaces

■ Q16. What is method overloading vs method overriding?


■ Answer: Overloading: same method name, different parameter list, in the same class, decided at compile time (static
polymorphism). Overriding: same method name, same parameters, in parent-child classes, decided at runtime
(dynamic polymorphism).

■ Example: Overloading: print(int), print(String), print(int,int) — all in same class. Overriding: [Link]() overridden in
[Link]().

■ Cross-Questions: Can you override static methods? Can you overload main()? What is @Override annotation?

■■ Common Mistake: Saying overloading changes return type only — return type alone cannot differentiate overloaded
methods.

■ Memory Trick: OverLOADing = LOAD different parameters. OverRIDING = RIDE over parent's method

■ Q17. What is the super keyword?


■ Answer: super refers to the parent class. Uses: 1) [Link]() — call parent's overridden method. 2)
[Link] — access parent's hidden variable. 3) super() — call parent's constructor (must be first line in child
constructor).

■ Example: Parent class: Animal. Child class: Dog. In Dog's constructor, super() calls Animal's constructor first.

■ Cross-Questions: Can super() and this() both be first line? When is super() automatically inserted?
■■ Common Mistake: Trying to put both super() and this() as first line — only one can be first.

■ Memory Trick: super = 'Hey Parent, I need your help'

■ Q18. What is polymorphism? Explain with example.


■ Answer: Polymorphism means 'many forms' — same action behaves differently based on the object. Compile-time
polymorphism: method overloading (resolved by compiler). Runtime polymorphism: method overriding (resolved by
JVM at runtime using dynamic method dispatch).

■ Example: [Link]() — if shape is Circle, draws circle. If Triangle, draws triangle. Same call, different behavior.

■ Cross-Questions: What is dynamic method dispatch? What is upcasting? What is instanceof operator?

■■ Common Mistake: Thinking overloading is runtime polymorphism — overloading is compile-time.

■ Memory Trick: Poly = Many, Morph = Forms. Same name, different behavior

■ Q19. What is abstraction? Difference between abstract class and interface?


■ Answer: Abstraction hides implementation details and shows only essential features. Abstract class: can have
abstract and concrete methods, can have constructors, fields. Interface: all methods are abstract by default (pre Java
8), no constructors, variables are public static final. A class can extend only one abstract class but implement multiple
interfaces.
■ Example: TV remote — you press power button (abstraction). You don't need to know internal circuits.

■ Cross-Questions: Can abstract class have constructor? Can interface have variables? What is default method in interface
(Java 8)?

■■ Common Mistake: Saying interface methods are private — they are public abstract by default.

■ Memory Trick: Abstract class = partial hiding. Interface = complete contract/blueprint

Abstract Class vs Interface

Feature Abstract Class Interface

Can have constructor Yes No

Method types Abstract + Concrete Abstract (default methods in Java 8+)

Variables Any type public static final only

Multiple inherit No Yes (multiple interfaces)

extends/implements extends implements

When to use IS-A with shared code CAN-DO contract

■ Q20. What are access modifiers in Java?


■ Answer: Java has 4 access modifiers: public (accessible everywhere), protected (same package + subclasses),
default/package-private (same package only), private (same class only). Most restrictive: private. Least restrictive:
public.

■ Example: public = open door. protected = family only. default = neighbors. private = your room.

■ Cross-Questions: Can private method be inherited? What is default access modifier? Can class be private?

■■ Common Mistake: Saying protected means private — protected allows subclass access.

■ Memory Trick: Public Protected Default Private — from open to closed: PPDP

Access Modifiers Visibility

Modifier Same Class Same Package Subclass Everywhere

private ■ ■ ■ ■

default ■ ■ ■ ■

protected ■ ■ ■ ■

public ■ ■ ■ ■

■ Q21. What is encapsulation? How is it achieved?


■ Answer: Encapsulation is the process of wrapping data (variables) and code (methods) into a single unit (class) and
restricting direct access to data using private access modifier. It is achieved by: 1) Declaring variables as private. 2)
Providing public getter and setter methods.

■ Example: Bank account — balance is private. You can only check or modify it through deposit() and withdraw() methods.

■ Cross-Questions: What is data hiding? Is encapsulation same as data hiding? What is a JavaBean?

■■ Common Mistake: Making variables public and calling it encapsulation — that defeats the purpose.

■ Memory Trick: Encapsulation = Capsule — everything packed inside, controlled access from outside

■■ Q22. Can we override the main() method in Java?


■ Answer: No, we cannot override main() because it is static, and static methods cannot be overridden (they can be
hidden). We can overload main() by providing different parameters, but the JVM only calls public static void
main(String[] args).

■ Example: You can write main(int x) but JVM will not call it automatically.

■ Cross-Questions: What is method hiding? Can main() be private? Can we have two main() methods?

■■ Common Mistake: Thinking overloading main() changes which one JVM calls — JVM always calls String[] args version.

■ Memory Trick: main() is STATIC — static methods are HIDDEN not OVERRIDDEN
UNIT 3

EXCEPTION HANDLING & MULTITHREADING


try-catch-finally • throw/throws • Thread Lifecycle • Synchronization

■ Exception Handling Questions

■ Q23. What is an exception? Difference between error and exception?


■ Answer: Exception is an abnormal event that disrupts normal program flow — can be handled. Error is a serious
problem (usually hardware/JVM level) that cannot be handled (StackOverflowError, OutOfMemoryError). Exceptions
extend Exception class; Errors extend Error class. Both extend Throwable.

■ Example: Exception: file not found (you can handle it). Error: computer out of RAM (you cannot handle it).

■ Cross-Questions: What is Throwable? What is the hierarchy of exception classes? Can we catch Error?

■■ Common Mistake: Saying Error and Exception are the same — they are different branches of Throwable.

■ Memory Trick: Exception = Handleable problem. Error = Unhandleable disaster

■ Q24. Explain try-catch-finally block.


■ Answer: try: code that might throw exception. catch: handles the exception. finally: always executes whether
exception occurs or not — used for cleanup (closing files/connections). You can have multiple catch blocks. Order:
specific exception before general Exception.

■ Example: try{open file} catch(FileNotFound){handle error} finally{close file — always}

■ Cross-Questions: Can finally block be skipped? What if [Link]() is called in try? Can try exist without catch?

■■ Common Mistake: Putting general Exception catch block before specific catch — compiler error.

■ Memory Trick: try=attempt, catch=handle, finally=ALWAYS cleanup

■ Q25. What is the difference between throw and throws?


■ Answer: throw: used inside a method body to manually throw an exception object — throw new
ArithmeticException('msg'). throws: used in method signature to declare that this method might throw a checked
exception — void readFile() throws IOException.

■ Example: throw = I am throwing this exception NOW. throws = Warning: this method MIGHT throw an exception.
■ Cross-Questions: Can we throw multiple exceptions? Can we throw Error? What is re-throwing?

■■ Common Mistake: Writing throws inside method body or throw in method signature — they are swapped.

■ Memory Trick: throw=action(verb). throws=declaration(warning label)

■ Q26. What are checked vs unchecked exceptions?


■ Answer: Checked exceptions: checked at compile time — must be handled with try-catch or declared with throws.
Examples: IOException, SQLException, ClassNotFoundException. Unchecked exceptions: occur at runtime — no
mandatory handling. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException. All
RuntimeException subclasses are unchecked.

■ Example: Checked = Seatbelt law (mandatory). Unchecked = Speed limit (ignored at your risk).

■ Cross-Questions: Is NullPointerException checked or unchecked? Why are runtime exceptions unchecked?

■■ Common Mistake: Saying all exceptions must be caught — only checked exceptions must be.
■ Memory Trick: Checked = Compiler forces you. Unchecked = Runtime surprise

■ Q27. How do you create a custom exception?


■ Answer: Create a class that extends Exception (for checked) or RuntimeException (for unchecked). Override
constructor to pass message. Use throw to throw it.

■ Example: class InsufficientFundsException extends Exception { InsufficientFundsException(String msg){ super(msg); } }

■ Cross-Questions: When would you create a custom exception? What does super(msg) do here?

■■ Common Mistake: Not calling super(msg) — the getMessage() will return null.

■ Memory Trick: Custom Exception = Extend Exception class + pass message to super()

■ Multithreading Questions

■ Q28. What is multithreading? What are its advantages?


■ Answer: Multithreading is executing multiple threads simultaneously within a single program. Advantages: better
CPU utilization, faster execution, responsive UI (GUI stays responsive while background task runs), resource sharing
between threads.

■ Example: Browser loading page + playing video + downloading file simultaneously — different threads.
■ Cross-Questions: What is a process vs thread? What is the main thread in Java? Is multithreading truly parallel?

■■ Common Mistake: Confusing process (separate memory) with thread (shared memory within same process).

■ Memory Trick: Multi = Many, Threading = Execution paths in ONE program

■ Q29. How do you create a thread in Java? Two ways?


■ Answer: Way 1: Extend Thread class — override run() method, create object, call start(). Way 2: Implement
Runnable interface — implement run() method, pass to Thread constructor, call start(). Runnable is preferred because
Java supports single inheritance — using Runnable lets your class extend another class too.

■ Example: class MyThread extends Thread{ public void run(){...}} new MyThread().start();

■ Cross-Questions: Why call start() and not run() directly? What happens if you call run() directly?

■■ Common Mistake: Calling run() directly — this executes in current thread, no new thread created. Always call start().

■ Memory Trick: Always call start() — it creates new thread and calls run() internally

■ Q30. Explain the thread lifecycle (states).


■ Answer: A thread goes through: NEW (created but not started), RUNNABLE (start() called, ready to run), RUNNING
(CPU allocated, executing), BLOCKED/WAITING (waiting for resource or another thread), TERMINATED/DEAD (run()
method completed). Transitions: NEW→RUNNABLE via start(), RUNNABLE↔BLOCKED for synchronization,
RUNNING→TERMINATED when run() ends.

■ Example: Like a job application: Applied(New)→Shortlisted(Runnable)→Interview(Running)→Waiting for


HR(Blocked)→Hired/Rejected(Terminated).

■ Cross-Questions: What is the difference between BLOCKED and WAITING? Can a terminated thread be restarted?

■■ Common Mistake: Saying a terminated thread can be restarted — it cannot. Create a new thread object.

■ Memory Trick: NEW→START→RUNNABLE→CPU→RUNNING→DONE→DEAD

■ Q31. What is synchronization? Why is it needed?


■ Answer: Synchronization is a mechanism to control access of multiple threads to shared resources. Without
synchronization, multiple threads can corrupt shared data (race condition). Use synchronized keyword on method or
block. Only one thread can execute a synchronized method on an object at a time.
■ Example: Two people withdrawing money from same account simultaneously without synchronization can cause negative
balance.

■ Cross-Questions: What is a race condition? What is a deadlock? What is the synchronized block vs method?

■■ Common Mistake: Synchronizing everything — over-synchronization kills performance. Synchronize only critical sections.

■ Memory Trick: Synchronized = One thread at a time — like a toilet with ONE lock

■■ Q32. What is deadlock in Java?


■ Answer: Deadlock is a situation where two or more threads are waiting for each other to release locks, and none can
proceed. Thread A holds lock1, waits for lock2. Thread B holds lock2, waits for lock1. Neither can proceed — both
stuck forever.

■ Example: Two people standing in narrow corridor, each waiting for the other to step aside — neither moves.

■ Cross-Questions: How to avoid deadlock? What is livelock? What is starvation?

■■ Common Mistake: Not knowing how to avoid deadlock — answer: acquire locks in consistent order, use tryLock().

■ Memory Trick: Deadlock = Circular waiting = Two threads hugging each other, neither lets go

Thread class vs Runnable interface

Feature Thread class Runnable interface

Inheritance Extends Thread (uses up one Implements Runnable (class can


inheritance) extend another)

Flexibility Less flexible More flexible — preferred approach

Code reuse Thread code mixed with task Task logic separated in Runnable

Usage new MyThread().start() new Thread(new MyRunnable()).start()


UNIT 4

FILE HANDLING & COLLECTIONS


Streams • Serialization • ArrayList • HashMap • Iterator

■ File Handling Questions

■ Q33. What are streams in Java? Types?


■ Answer: Stream is a sequence of data. Two types: Byte streams (read/write binary data —
InputStream/OutputStream) and Character streams (read/write text data — Reader/Writer). For text files use
FileReader/FileWriter. For binary files use FileInputStream/FileOutputStream. BufferedReader/BufferedWriter wrap
character streams for efficiency.

■ Example: FileReader like reading letter one character at a time. BufferedReader = reading full lines at once.

■ Cross-Questions: What is the difference between FileReader and BufferedReader? Why use Buffered streams?

■■ Common Mistake: Using byte streams for text files — use character streams for text.

■ Memory Trick: Byte Streams = Binary(images/audio). Character Streams = Text(letters, files)

■ Q34. What is serialization in Java?


■ Answer: Serialization is converting an object into a byte stream to save to file or send over network. Deserialization
is the reverse — converting byte stream back to object. Class must implement Serializable interface. Use
ObjectOutputStream for serialization, ObjectInputStream for deserialization. serialVersionUID is used for version
control.

■ Example: Like converting a 3D sculpture into a flat image (serialize) and reconstructing it (deserialize).

■ Cross-Questions: What is transient keyword? What is serialVersionUID? What if a field is not serializable?

■■ Common Mistake: Forgetting to implement Serializable — causes NotSerializableException.

■ Memory Trick: Serializable = Object can be saved. transient = Don't save this field

■ Collections Framework Questions

■ Q35. What is the Collections Framework? Why use it instead of arrays?


■ Answer: Collections Framework is a set of classes and interfaces that provide ready-made data structures.
Advantages over arrays: Dynamic size (no fixed size), built-in methods (sort, search), type safety with generics. Key
interfaces: List, Set, Map, Queue. Arrays have fixed size; collections grow dynamically.

■ Example: Array = fixed parking lot. ArrayList = expandable parking — adds slots automatically.

■ Cross-Questions: What is the root interface of Collections? Is Map a Collection? What is the difference between Collection
and Collections?

■■ Common Mistake: Confusing Collection (interface) with Collections (utility class with sort(), shuffle() etc.)

■ Memory Trick: Collections = Dynamic, Flexible, Ready-made Data Structures

■ Q36. Difference between ArrayList and LinkedList?


■ Answer: ArrayList: backed by dynamic array, fast random access O(1), slow insert/delete in middle O(n). LinkedList:
backed by doubly linked list, slow random access O(n), fast insert/delete at head/tail O(1). Use ArrayList for frequent
access, LinkedList for frequent insert/delete.
■ Example: ArrayList = Row of seats (get seat 5 instantly). LinkedList = Chain of people holding hands (must count from
start).

■ Cross-Questions: When would you choose LinkedList over ArrayList? What is the initial capacity of ArrayList?

■■ Common Mistake: Using LinkedList when random access is needed — ArrayList is faster for that.

■ Memory Trick: ArrayList = Array + Dynamic. LinkedList = Chain of nodes

■ Q37. What is HashMap? How does it work?


■ Answer: HashMap stores key-value pairs. Uses hashing — key's hashCode() determines bucket position. Allows
one null key and multiple null values. Not synchronized. Not ordered. Time complexity: O(1) average for put() and
get(). Internally uses array of LinkedLists (or trees in Java 8+).

■ Example: Phone directory: name(key) → phone number(value). Hash = first letter decides which page.

■ Cross-Questions: What happens when two keys have same hashCode? What is collision? What is load factor?

■■ Common Mistake: Confusing HashMap with HashSet. HashMap = key-value pairs. HashSet = unique values only.

■ Memory Trick: HashMap = Key→Value, Hash decides the bucket/position

■ Q38. What is the difference between HashMap, LinkedHashMap, and TreeMap?


■ Answer: HashMap: no order, O(1) operations. LinkedHashMap: maintains insertion order, slightly slower. TreeMap:
sorted by keys (natural or custom comparator), O(log n) operations. Use HashMap for performance, LinkedHashMap
for insertion-order iteration, TreeMap for sorted keys.

■ Example: HashMap=random bag, LinkedHashMap=queue bag(order preserved), TreeMap=alphabetically sorted bag.

■ Cross-Questions: What is the default capacity of HashMap? What is the difference between HashMap and Hashtable?

■■ Common Mistake: Saying HashMap is ordered — it is NOT ordered (LinkedHashMap is).

■ Memory Trick: Hash=Fast. LinkedHash=Ordered. Tree=Sorted

■ Q39. What is the difference between HashSet and TreeSet?


■ Answer: HashSet: no order, O(1) add/contains/remove, allows one null. TreeSet: sorted order, O(log n) operations,
no null allowed. Both store unique elements only — no duplicates. HashSet uses HashMap internally; TreeSet uses
TreeMap internally.

■ Example: HashSet=random basket(unique). TreeSet=sorted rack(unique, alphabetical).

■ Cross-Questions: How does HashSet ensure uniqueness? What methods does Set use to check duplicates?

■■ Common Mistake: Thinking Set allows duplicates — Set strictly stores unique elements.

■ Memory Trick: HashSet=Unique+Fast. TreeSet=Unique+Sorted

■ Q40. How does Iterator work in Java?


■ Answer: Iterator is an interface that allows traversing a collection one element at a time. Methods: hasNext() (returns
true if more elements), next() (returns next element and advances pointer), remove() (removes last returned element).
Use for-each loop for simple iteration; use Iterator when you need to remove elements during iteration.

■ Example: Like a pointer moving through a list — check if next exists, then get next.

■ Cross-Questions: Can you modify a collection while iterating with for-each? What is ConcurrentModificationException?

■■ Common Mistake: Modifying collection with for-each loop — causes ConcurrentModificationException. Use
[Link]().

■ Memory Trick: Iterator: hasNext()→next()→remove() — Check, Get, Remove

Collections Comparison

Class Interface Access Sorted Null


ArrayList List Index-based No Yes

LinkedList List/Deque Sequential No Yes

HashMap Map Key-Value No No

TreeMap Map Key-Value Yes(key) No

HashSet Set Unique values No No(one null)

TreeSet Set Unique+sorted Yes No

LinkedList Queue FIFO No Yes


UNIT 5

ADVANCED JAVA — GUI & JDBC


AWT • Swing • Event Handling • JDBC • Database Connectivity

■ AWT and Swing Questions

■ Q41. What is AWT? What is Swing? What is the difference?


■ Answer: AWT (Abstract Window Toolkit): Java's original GUI toolkit, uses native OS components (heavyweight),
limited components, platform-dependent look. Swing: built on top of AWT, uses pure Java components (lightweight),
more components (JTable, JTree, etc.), pluggable look and feel, platform-independent appearance. Swing is preferred
for modern Java desktop applications.

■ Example: AWT = using local restaurant (OS look). Swing = your own restaurant (consistent look everywhere).

■ Cross-Questions: Is JavaFX better than Swing? What is heavyweight vs lightweight component? What is MVC in Swing?

■■ Common Mistake: Confusing AWT and Swing as separate systems — Swing extends AWT.

■ Memory Trick: AWT=Native(OS-dependent). Swing=Pure Java(consistent look)

■ Q42. What is event handling in Java? Explain the delegation event model.
■ Answer: Event handling responds to user actions (button click, key press). Delegation Event Model: Event Source
(button) → Event Object (ActionEvent) → Event Listener (ActionListener) → Event Handler (actionPerformed method).
Steps: 1) Implement listener interface. 2) Override event method. 3) Register listener on component with
addActionListener().

■ Example: Button click → ActionEvent object created → [Link]() called.

■ Cross-Questions: What is ActionListener? What is MouseListener? What are the methods in ActionListener?

■■ Common Mistake: Registering listener but not adding it to component — event never fires.

■ Memory Trick: Source→Event→Listener→Handler — SELH: Source Event Listener Handle

■ Q43. What is the difference between JFrame and JPanel?


■ Answer: JFrame is the main window of a Swing application — it has title bar, borders, close button. JPanel is a
container used to group components inside JFrame. JPanel has no border/title bar. Multiple JPanels can be placed
inside a JFrame to organize layout.

■ Example: JFrame = house. JPanel = rooms inside the house.

■ Cross-Questions: What is ContentPane? What is a layout manager? What is BorderLayout?

■■ Common Mistake: Adding components directly to JFrame — should add to JFrame's content pane.

■ Memory Trick: JFrame=Window, JPanel=Container inside window

■ JDBC Questions

■ Q44. What is JDBC? Explain the JDBC architecture.


■ Answer: JDBC (Java Database Connectivity) is a Java API to connect and execute queries on databases.
Architecture: Java Application → JDBC API → JDBC Driver Manager → JDBC Driver → Database. 4 types of drivers:
Type 1(JDBC-ODBC bridge), Type 2(Native API), Type 3(Network Protocol), Type 4(Thin/Pure Java — most used).
Steps: Load driver → Get Connection → Create Statement → Execute Query → Process ResultSet → Close.
■ Example: JDBC = bridge between Java code and MySQL/Oracle database.

■ Cross-Questions: Which JDBC driver type is most commonly used and why? What is connection pooling?

■■ Common Mistake: Not closing Connection/Statement/ResultSet — causes resource leak. Always close in finally.

■ Memory Trick: JDBC Steps: Load-Connect-Statement-Execute-Process-Close (LC-SEC)

■ Q45. Explain the 5 steps to connect Java to a database using JDBC.


■ Answer: Step 1: Load/Register driver — [Link]('[Link]'). Step 2: Get Connection —
[Link](url, user, password). Step 3: Create Statement — [Link](). Step
4: Execute query — [Link]('SELECT * FROM table'). Step 5: Process ResultSet —
while([Link]()){[Link]('name');}. Always close in finally block.

■ Example: Like dialing a phone: dial(load


driver)→connect(getConnection)→speak(statement)→listen(resultset)→hangup(close).

■ Cross-Questions: What is a PreparedStatement? What is the difference between executeQuery() and executeUpdate()?

■■ Common Mistake: Using executeQuery() for INSERT/UPDATE — use executeUpdate() for DML, executeQuery() for
SELECT.

■ Memory Trick: Load→Connect→Statement→Execute→ResultSet→Close

■ Q46. What is the difference between Statement and PreparedStatement?


■ Answer: Statement: plain SQL string, compiled every time, vulnerable to SQL injection. PreparedStatement:
precompiled SQL with placeholders (?), compiled once, faster for repeated queries, protects against SQL injection.
Prefer PreparedStatement always.

■ Example: Statement: 'SELECT * FROM users WHERE name='+ userInput (injection risk!). PreparedStatement: 'SELECT *
FROM users WHERE name=?' then [Link](1, userInput).

■ Cross-Questions: What is CallableStatement? What is SQL injection? How does PreparedStatement prevent injection?

■■ Common Mistake: Using Statement for user input queries — always use PreparedStatement for security.

■ Memory Trick: PreparedStatement = Pre-cooked with placeholders = Faster + Safer

■ Q47. What is ResultSet in JDBC?


■ Answer: ResultSet is an object that holds the data returned by a SELECT query. It works as a cursor that points
before first row initially. Methods: next() — moves to next row and returns true if row exists.
getString(columnName/index), getInt(), getDouble() — retrieve column values. Types: TYPE_FORWARD_ONLY
(default), TYPE_SCROLL_INSENSITIVE (can scroll), TYPE_SCROLL_SENSITIVE.

■ Example: ResultSet = table result in memory, cursor starts before row 1, [Link]() moves to each row.

■ Cross-Questions: Can you update data through ResultSet? What is a scrollable ResultSet?

■■ Common Mistake: Forgetting [Link]() before getting values — starts before first row.

■ Memory Trick: ResultSet cursor starts BEFORE row 1. Always call next() first.

JDBC Statement Types

Type SQL Format Precompiled Compile Security Use When

Statement Plain SQL No Every time Low Simple static


queries

PreparedStateme SQL with ? Yes Once High Repeated/user-in


nt put queries

CallableStatemen Stored Yes Once High DB stored


t procedures procedures
■ TOP 25 ALMOST-GUARANTEED VIVA QUESTIONS

1. What is platform independence in Java? Bytecode runs on any OS with JVM — WORA principle.

2. Explain JVM vs JRE vs JDK JDK⊃JRE⊃JVM. JDK for dev, JRE for run, JVM executes
bytecode.

3. What are the 4 OOP pillars? Encapsulation, Inheritance, Polymorphism, Abstraction

4. Class vs Object Class=blueprint, Object=instance with actual memory

5. Constructor vs Method Constructor: same name as class, no return type,


auto-called. Method: has return type, called explicitly.

6. What is this keyword? Refers to current object. Used to resolve name ambiguity.

7. What is super keyword? Refers to parent class. super() calls parent constructor.

8. Overloading vs Overriding Overloading=same class+diff params.


Overriding=parent-child+same signature.

9. What is encapsulation? Private variables + public getters/setters. Data hiding.

10. Abstract class vs Interface Abstract: partial impl, one extends. Interface: full contract,
multiple implements.

11. Checked vs Unchecked exceptions Checked=compile-time (IOException).


Unchecked=runtime (NullPointer).

12. throw vs throws throw=actually throw exception. throws=declare method


may throw.

13. What does finally do? Always executes — cleanup code (close
files/connections).

14. Create thread — 2 ways Extend Thread OR Implement Runnable. Runnable


preferred.

15. Why call start() not run()? start() creates new thread. run() executes in current
thread.

16. What is synchronization? Controls concurrent access to shared resource. One


thread at a time.

17. ArrayList vs LinkedList ArrayList=fast access. LinkedList=fast insert/delete.

18. HashMap vs HashSet HashMap=key-value pairs. HashSet=unique values only.

19. What is Iterator? Interface to traverse collection. hasNext(), next(),


remove().

20. What is serialization? Object→byte stream for saving/transmission. Implement


Serializable.

21. JDBC 5 steps Load driver→Connect→Statement→Execute→ResultSet


→Close

22. Statement vs PreparedStatement Statement=plain SQL. PreparedStatement=precompiled,


safe, faster.

23. What is AWT vs Swing? AWT=native(heavyweight). Swing=pure Java(lightweight,


consistent).
24. What is event handling? Source→Event→Listener→Handler. Delegation Event
Model.

25. What is the difference between == and ==compares reference. .equals() compares
.equals()? content/value.
■ RAPID-FIRE ONE-LINE ANSWERS

Q: What does JVM stand for? A: Java Virtual Machine

Q: What is bytecode? A: Intermediate code produced by Java compiler, runs on


JVM

Q: What is WORA? A: Write Once Run Anywhere — Java's platform


independence principle

Q: Size of int in Java? A: 4 bytes (32 bits)

Q: Size of char in Java? A: 2 bytes (16 bits) — uses Unicode

Q: Is String mutable? A: No — String is immutable in Java

Q: Which is mutable: StringBuilder or A: Both are mutable. StringBuilder is faster (not thread-safe)
StringBuffer?

Q: What is null? A: Default value for object reference — points to nothing

Q: What is static? A: Belongs to class, not object — shared among all instances

Q: Can constructor be static? A: No — constructors are called on objects, not class

Q: What is final keyword? A: final variable=constant, final method=cannot override, final


class=cannot inherit

Q: Can we instantiate abstract class? A: No — abstract class cannot be instantiated directly

Q: Default value of boolean? A: false

Q: What is garbage collection? A: Automatic memory management — JVM removes unused


objects

Q: What is NullPointerException? A: Occurs when you use a reference variable that points to
null

Q: What is ClassCastException? A: Occurs when you cast object to incompatible type

Q: What is the root class in Java? A: Object class — all classes implicitly extend Object

Q: What is toString()? A: Method of Object class — returns string representation of


object

Q: What is hashCode()? A: Returns integer hash value of object — used in HashMap

Q: What is autoboxing? A: Automatic conversion of primitive to wrapper class


(int→Integer)

Q: What is unboxing? A: Automatic conversion of wrapper class to primitive


(Integer→int)

Q: What is a wrapper class? A: Class wrapping primitive type: Integer, Double, Boolean,
Character

Q: What is the difference between List and Set? A: List allows duplicates + ordered. Set no duplicates.

Q: What is Queue? A: FIFO data structure. LinkedList implements Queue.

Q: What is Stack? A: LIFO data structure. Deque/ArrayDeque preferred over


Stack class.

Q: What does [Link]() return? A: true if next row exists, false if no more rows

Q: What is a deadlock? A: Two threads waiting for each other's locked resources —
stuck forever

Q: What is thread priority? A: 1(MIN) to 10(MAX), default 5. Higher priority gets CPU
first (not guaranteed)

Q: What is sleep() in Thread? A: Pauses thread for specified milliseconds. Throws


InterruptedException
Q: What does join() do? A: Waits for a thread to complete before current thread
continues
■ MOCK VIVA CONVERSATION — Unit 1 & 2

■ Examiner: Good morning. Tell me, what is Java?


■■■ Student: Good morning sir. Java is a high-level, object-oriented, platform-independent programming language
developed by James Gosling at Sun Microsystems in 1995. Its main feature is WORA — Write Once Run Anywhere.
■ Examiner: What do you mean by platform-independent?
■■■ Student: Sir, when we compile Java code, it produces bytecode — not machine code. This bytecode can run on
any operating system that has a JVM installed. So the same .class file runs on Windows, Linux, and Mac without any
change.
■ Examiner: So is JVM platform-independent?
■■■ Student: No sir, JVM itself is platform-specific — there is a different JVM for each operating system. But the
bytecode it runs is platform-independent. So Java code is platform-independent, not the JVM.
■ Examiner: Good. What is the difference between JDK, JRE and JVM?
■■■ Student: Sir, JVM is the engine that executes bytecode. JRE includes JVM plus the standard libraries needed to
run Java programs — it is for end users. JDK includes JRE plus development tools like the compiler javac and debugger
— it is for developers.
■ Examiner: What are the 4 pillars of OOP?
■■■ Student: Sir, the four pillars are: Encapsulation — wrapping data and methods, hiding data using private access.
Inheritance — child class acquiring properties of parent class. Polymorphism — same method behaving differently
based on object. Abstraction — hiding internal complexity and showing only essential features.
■ Examiner: Can you give a real-world example of polymorphism?
■■■ Student: Yes sir. Consider a shape class with a draw() method. When the shape is a circle, draw() draws a circle.
When it is a triangle, draw() draws a triangle. Same method name, different behavior based on the actual object type —
that is runtime polymorphism.
■ Examiner: What is the difference between method overloading and overriding?
■■■ Student: Sir, method overloading is in the same class with same method name but different parameters — it is
compile-time polymorphism. Method overriding is in parent-child relationship where the child redefines the parent's
method with same signature — it is runtime polymorphism.
■ Examiner: Very good. Can you override a static method?
■■■ Student: No sir, static methods cannot be overridden — they can only be hidden. Overriding requires dynamic
dispatch which needs an object, but static methods belong to the class, not the object. If we define the same static
method in child class, it is called method hiding, not overriding.
■ Examiner: Excellent. Thank you.
■■■ Student: Thank you sir.
■■ TRICKY QUESTIONS USED TO FAIL STUDENTS

■■ Can we have a class without any method? Yes — a class can have only fields and no methods. It
is still valid Java.

■■ Can constructor return a value? No return statement, but constructor implicitly returns
the newly created object.

■■ Can we catch multiple exceptions in one catch? Yes — catch(IOException | SQLException e) using |
operator (Java 7+).

■■ What if both try and finally have return? finally's return overrides try's return — always.

■■ Is Java fully object-oriented? No — primitive types (int, char, etc.) are not objects.

■■ Can interface have a constructor? No — interfaces cannot have constructors since they
cannot be instantiated.

■■ Can abstract class have a constructor? Yes — called by subclass using super(). Abstract
class itself is not instantiated.

■■ What is output of 5/2 in Java? 2 (integer division). For 2.5, use 5.0/2 or (double)5/2.

■■ Can we change the value of a final variable? No — final variable is a constant. Reassignment
causes compile error.

■■ What happens if main() throws an exception? JVM catches it, prints stack trace, and terminates the
program.

■■ Can two threads call synchronized methods Yes — synchronized is per-object, different objects
simultaneously on different objects? have different locks.

■■ What is output: String s=null; [Link]()? NullPointerException — cannot call method on null
reference.

■■ Is null a keyword in Java? Yes — null is a literal (like true and false), not exactly
a keyword but a reserved word.

■■ Can ArrayList store primitives? No — only objects. Use Integer, Double etc.
(autoboxing converts automatically).
■ IF STUDENT GETS STUCK — RECOVERY ANSWERS

Situation Recovery Answer to Speak

You forgot the exact definition Sir, I know the concept practically — let me explain with an example...

You made a wrong answer Sorry sir, I made an error. The correct answer is...

You don't know at all Sir, I am not fully sure about that specific point, but I know that...

Examiner pushes with Sir, from what I understand, the key idea is... and in practice it works
cross-question like...

Confused between two concepts Sir, both are related — the key difference I remember is...

Asked about code you forgot Sir, I remember the logic. The code structure would be: try the
operation, catch the exception, and finally close resources.

■ LAST-MINUTE REVISION NOTES

1. Java = OOP + Platform-Independent + JVM executes bytecode


2. JDK > JRE > JVM (developer kit > runtime > virtual machine)
3. 4 OOP pillars: EIPA — Encapsulation, Inheritance, Polymorphism, Abstraction
4. Overloading = compile-time, same class, diff params | Overriding = runtime, parent-child, same signature
5. abstract class = extends (one) | interface = implements (many)
6. Checked exceptions = compile-time (IOException) | Unchecked = runtime (NullPointer, ArrayIndexOutOfBounds)
7. throw = action | throws = declaration in method signature
8. finally ALWAYS runs (unless [Link]() called)
9. Thread: start() creates new thread | run() just calls method in same thread
10. Synchronized = one thread at a time per object lock
11. ArrayList = fast get() | LinkedList = fast add/remove at ends
12. HashMap = key-value, no order | LinkedHashMap = insertion order | TreeMap = sorted keys
13. JDBC: Load→Connect→Statement→Execute→ResultSet→Close
14. PreparedStatement preferred — precompiled + SQL injection safe
15. AWT = heavyweight (native) | Swing = lightweight (pure Java)
16. String = immutable | StringBuilder = mutable, fast | StringBuffer = mutable, thread-safe
17. == checks reference | .equals() checks value/content
18. Constructors have NO return type (not even void)
19. this = current object | super = parent class
20. final variable = constant | final method = no override | final class = no inherit

Java Viva Preparation Guide — Complete Engineering Exam Edition | All Units 1-5 | Good Luck!

You might also like