0% found this document useful (0 votes)
3 views28 pages

Java Complete 5university Notes

The document provides comprehensive notes on Java programming, covering topics from five universities including GJU, IGNOU, MDU, Osmania, and Mumbai. It includes detailed explanations of key concepts such as Java Bytecode, inheritance, polymorphism, exception handling, and multithreading, along with sample questions and answers. The notes are structured into units, each addressing different aspects of Java, making it a valuable resource for students preparing for exams.

Uploaded by

MayankLamba
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)
3 views28 pages

Java Complete 5university Notes

The document provides comprehensive notes on Java programming, covering topics from five universities including GJU, IGNOU, MDU, Osmania, and Mumbai. It includes detailed explanations of key concepts such as Java Bytecode, inheritance, polymorphism, exception handling, and multithreading, along with sample questions and answers. The notes are structured into units, each addressing different aspects of Java, making it a valuable resource for students preparing for exams.

Uploaded by

MayankLamba
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 PROGRAMMING

COMPLETE NOTES — GJU · IGNOU · MDU · OSMANIA · MUMBAI

PART A: GJU MCA-13 (Purple)

PART B: IGNOU MCS-024 (Green)

PART C1: MDU 20MCA21C1 (Red)

PART C2: Osmania PCC103 (Orange)

PART C3: Mumbai MCA11 (Blue)

63 Questions | 5 Universities | Fully Explained with Code & Tables

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 1


TOPIC FREQUENCY ACROSS ALL 5 UNIVERSITIES
Topic GJU IGNOU MDU Osmania Mumbai Priority
JVM / Bytecode / WORA ■ ■ ■ ■ ■ ■■■ ALL 5
Inheritance & Polymorphism ■ ■ ■ ■ ■ ■■■ ALL 5
OOP Concepts (EIPA) ■ ■ ■ ■ ■ ■■■ ALL 5
Exception Handling ■ ■ ■ ■ ■ ■■■ ALL 5
Abstract Class + Interface ■ ■ ■ ■ ■ ■■■ ALL 5
Multithreading ■ ■ ■ ■ ■ ■■■ ALL 5
AWT vs Swing ■ ■ ■ ■ ■ ■■■ ALL 5
String / StringBuffer ■ ■ ■ ■ ■ ■■■ ALL 5
final / finally / finalize ■ ■ ■ — — ■■ 4 Uni
Applet Lifecycle ■ ■ — ■ — ■■ 3 Uni
Access Modifiers — — ■ ■ ■ ■■ 3 Uni
Packages ■ — ■ ■ — ■■ 3 Uni
Wrapper Classes — — ■ — ■ ■ 2 Uni
super keyword — — ■ — ■ ■ 2 Uni
Collections Framework — — ■ ■ — MDU+Osmania
Singleton Pattern ■ — — — — GJU Only
Java Bean — ■ — — — IGNOU Only
RMI Architecture — ■ — — — IGNOU Only
Serialization — ■ — ■ — IGNOU+Osmania
Socket Programming — ■ — ■ — IGNOU+Osmania
Image Processing — — — ■ — Osmania Only
Iterator / Comparator — — — ■ — Osmania Only

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 2


PART A — GJU MCA-13 | JAVA PROGRAMMING
Guru Jambheshwar University · MCA-13 (Code 3032/17333) · Papers A-22 & D-23 · Q1 Compulsory + Any 4 from Q2–Q8 · 70 marks

UNIT I — Java Fundamentals

Q1. Explain Java Bytecode. What is JVM and how does Java achieve platform independence?
■ GJU A-22 Q.2(a) | D-23 Q.2(a) — BOTH PAPERS
■ APPEARS IN BOTH EXAM PAPERS

■ Answer:

What is Java Bytecode?


When you compile Java source (.java) with javac, it produces Bytecode (.class) — a platform-neutral intermediate format. The JVM on any OS reads the same
.class file and executes it natively. This gives Java WORA: Write Once Run Anywhere.
JVM Internal Components:
• Class Loader: loads .class bytecode into memory.
• Bytecode Verifier: checks security and validity before execution.
• JIT Compiler: compiles hot bytecode to native machine code for speed.
• Garbage Collector: auto-reclaims memory from unreferenced objects.
• JVM has 5 components: (1) Class Loader — loads .class into memory. (2) Bytecode Verifier — security checks. (3) JIT Compiler — compiles hot bytecode to native
code. (4) Garbage Collector — auto-reclaims heap memory. (5) Runtime Data Areas — Heap, Stack, Method Area, PC Register, Native Method Stack.
Component Contains Used by
JVM Class Loader + Bytecode Verifier + JIT + GC + Runtime Data Areas Both (runs programs)
JRE JVM + Standard Libraries ([Link], [Link], etc.) End users (run only)
JDK JRE + javac compiler + javadoc + tools Developers (compile+run)
javac [Link] // → [Link] (bytecode)
java HelloWorld // JVM reads bytecode → runs on any OS
■ EXAM TIP: Write: .java → javac → .class → JVM → Output. Mention WORA. List all 5 JVM components.

Q2. Define class and object. Differentiate between Java and C++.
■ GJU A-22 Q.1(a)(b) — COMPULSORY
■ COMPULSORY — GJU A-22

■ Answer:
Class: blueprint defining attributes + behaviours. No memory allocated for data.
Object: runtime instance of a class. Created with "new" — allocates heap memory.
class Student { String name; int roll; void show(){ [Link](name); } }
Student s = new Student(); [Link]="Ram"; [Link](); // Ram
Feature Java C++
Platform Platform-independent (JVM — WORA) Platform-dependent (native compiled code)
Memory management Automatic Garbage Collector — no free() Manual — new/delete required; risk of leaks
Pointers Hidden (references only — safe) Full pointer arithmetic — unsafe
Multiple Inheritance Via interfaces only — no diamond problem Directly allowed — diamond problem possible
Operator Overloading Not supported (except + for String concat) Fully supported
Header files Not needed — packages used .h header files required

Q3. What is a singleton class in Java? How to implement it?


■ GJU D-23 Q.1(a) — COMPULSORY
■ COMPULSORY — GJU D-23

■ Answer:
Singleton ensures only ONE instance exists. Achieved via: private constructor + private static instance + synchronized public getInstance().
class DatabaseManager {
private static DatabaseManager instance = null;
private DatabaseManager() { } // private constructor
public static synchronized DatabaseManager getInstance() {
if(instance == null) instance = new DatabaseManager();
return instance;
}
}
DatabaseManager db1 = [Link]();
DatabaseManager db2 = [Link]();
[Link](db1 == db2); // true — SAME object
■ NOTE: "synchronized" makes it thread-safe. Without it, two threads could create two instances simultaneously.

Q4. Explain in detail data types available in Java.


■ GJU A-22 Q.3(a)

■ Answer:
Type Size (bytes) Range Default
byte 1 −128 to +127 (256 values) 0

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 3


Type Size (bytes) Range Default
short 2 −32,768 to +32,767 0
int 4 −2,147,483,648 to +2,147,483,647 (−2^31 to 2^31−1) 0
long 8 −9.2×10^18 to +9.2×10^18 (−2^63 to 2^63−1) 0L
float 4 ±1.4×10^−45 to ±3.4×10^38 (7 decimal digits precision) 0.0f
double 8 ±4.9×10^−324 to ±1.7×10^308 (15 decimal digits precision) 0.0
char 2 0 to 65,535 (all Unicode chars — \u0000 to \uFFFF) \u0000
boolean 1 bit true or false (no numeric equivalent in Java) false
• Non-primitive: String, arrays, classes, interfaces — store reference (memory address) on Stack; object on Heap.
int age=25; double pi=3.14; char grade="A"; boolean ok=true;

Q5. Difference among static methods, static variables, and static classes.
■ GJU D-23 Q.1(b) — COMPULSORY
■ COMPULSORY — GJU D-23

■ Answer:
• Static variable: ONE copy shared by ALL objects. Exists before any object is created.
• Static method: belongs to class not object; called without creating object; cannot access instance members.
• Static nested class: can be instantiated without outer class object.
class Employee { static int count=0; Employee(){ count++; } }
Employee e1=new Employee(); Employee e2=new Employee();
[Link]([Link]); // 2
class MathHelper { static double square(double n){ return n*n; } }
[Link](5); // 25.0 — no object needed

Q6. Why is multiple inheritance not supported in Java? Explain Diamond Problem.
■ GJU D-23 Q.1(d) — COMPULSORY
■ COMPULSORY — GJU D-23

■ Answer:
Diamond Problem: If class D extends B and C (both extending A and overriding show()), calling [Link]() is ambiguous — which version runs? Java avoids
this by disallowing multiple class inheritance.
Solution: Java allows multiple INTERFACE implementation. Interfaces define contracts only (no concrete state). If two interfaces have same default method,
implementing class MUST override: [Link]().
interface Printable { void print(); }
interface Saveable { void save(); }
class Document implements Printable, Saveable { // multiple OK
public void print(){ [Link]("Printing"); }
public void save() { [Link]("Saving"); }
}

UNIT II — Inheritance, Polymorphism, Interfaces & Threads

Q7. What is inheritance? Types? Explain polymorphism and abstract classes.


■ GJU D-23 Q.3(a) — 7 marks
■ FREQUENTLY ASKED — 7 MARKS

■ Answer:
Type Description
Single A → B (one child, one parent)
Multilevel A → B → C (chain)
Hierarchical A → B, A → C (multiple children)
Multiple Via interfaces only (Bat implements Flying, Mammal)
Polymorphism: Overloading=compile-time (same name, diff params). Overriding=runtime (child redefines parent method — dynamic dispatch).
class Animal { void sound(){ [Link]("..."); } }
class Dog extends Animal { void sound(){ [Link]("Woof!"); } }
class Cat extends Animal { void sound(){ [Link]("Meow!"); } }
Animal a = new Dog(); [Link](); // Woof! — dynamic dispatch
a = new Cat(); [Link](); // Meow! — same reference, different type
abstract class Shape { abstract double area(); }
class Circle extends Shape { double r; double area(){ return [Link]*r*r; } }

Q8. What is multithreading? Thread creation, lifecycle and priorities.


■ GJU A-22 & D-23 Q.5(b) — BOTH PAPERS
■ APPEARS IN BOTH PAPERS

■ Answer:
Multithreading: concurrent execution of multiple threads sharing heap memory within one process.
State Description
New Thread created — start() not called yet

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 4


State Description
Runnable start() called — waiting for CPU
Running Executing on CPU
Blocked/Waiting sleep()/wait()/join() called
Terminated run() returned or exception
class DownloadThread extends Thread {
String file;
DownloadThread(String f){ file=f; }
public void run() {
for(int i=10;i<=100;i+=10){
[Link](file+" "+i+"%");
try{ [Link](500); }catch(InterruptedException e){}
}
}
}
new DownloadThread("movie.mp4").start(); // ALWAYS start() not run()
• Priorities: MIN_PRIORITY=1 | NORM_PRIORITY=5 (default) | MAX_PRIORITY=10

Q9. Do final, finally and finalize have the same function? Discuss.
■ GJU D-23 Q.4(a) — 7 marks

■ Answer:
Keyword Type Purpose Runs when
final Keyword var=constant (cannot reassign); method=no override; class=no extend Compile-time enforcement
finally Block Guaranteed cleanup code after try-catch ALWAYS runs — even if
return/exception in try
finalize() Method Last cleanup before Garbage Collector destroys object. Deprecated Java Called by GC just before
9+. object memory reclaimed
final int MAX=100; // cannot reassign
try{ f=openFile(); return process(); }
catch(Exception e){ }
finally{ [Link](); } // ALWAYS closes file
protected void finalize() throws Throwable { releaseResource(); [Link](); }

Q10. Differences between interfaces and abstract classes.


■ GJU D-23 Q.4(b) — 7 marks

■ Answer:
Feature Abstract Class Interface
Constructor Yes No
Instance variables Allowed No — only public static final
Methods Abstract + concrete Abstract (Java 7); + default/static (Java 8+)
Inheritance Single (extends) Multiple (implements)
Use when IS-A + shared code CAN-DO contract, multiple types
interface Drawable { void draw(); }
interface Colorable { void fill(String c); }
class Rect implements Drawable, Colorable { // multiple interfaces
public void draw(){ [Link]("Drawing"); }
public void fill(String c){ [Link]("Color: "+c); }
}

UNIT III — Exception Handling & I/O

Q11. Write a Java program illustrating try, catch, throw and finally.
■ GJU A-22 Q.6(a)

■ Answer:
Exception hierarchy: Throwable → Error (do not catch) | Exception → Checked (IOException, SQLException) | RuntimeException=Unchecked (NPE,
ArithmeticException)
• throw: inside method body — throws an instance. throws: in signature — declares what method may throw.
static void withdraw(double bal, double amt) throws ArithmeticException {
if(amt>bal) throw new ArithmeticException("Insufficient funds: "+bal);
[Link]("Withdrawn. New bal: "+(bal-amt));
}
try { withdraw(1000, 1500); }
catch(ArithmeticException e){ [Link]("Error: "+[Link]()); }
finally { [Link]("Transaction session ended — always runs"); }

Q12. Explain input and output stream classes in Java.


■ GJU A-22 Q.7 — 14 marks
■ 14 MARKS — WRITE IN DETAIL

■ Answer:

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 5


Stream Type Input Classes Output Classes Used for
Byte FileInputStream, BufferedInputStream, FileOutputStream, BufferedOutputStream, Binary (images, audio, video)
DataInputStream DataOutputStream
Character FileReader, BufferedReader, InputStreamReader FileWriter, BufferedWriter, PrintWriter Text (Unicode,
human-readable)
// Read text file line by line:
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while((line = [Link]()) != null) [Link](line);
[Link]();
■ NOTE: Always close streams in finally or use try-with-resources: try(BufferedReader br = ...) { }

Q13. Difference between String and StringBuffer.


■ GJU A-22 Syllabus Unit III

■ Answer:
Feature String StringBuffer StringBuilder
Mutable? No — immutable Yes — mutable Yes — mutable
Thread-safe? Yes (immutable) Yes (synchronized) No — fastest
Use case Fixed text Multi-thread text ops Single-thread text ops
String s = ""; for(int i=0;i<1000;i++) s+=i; // 1000 new objects — BAD
StringBuffer sb = new StringBuffer();
for(int i=0;i<1000;i++) [Link](i); // ONE object — GOOD
String result = [Link]();
• Key StringBuffer methods: append(x), insert(i,x), delete(s,e), reverse(), replace(s,e,str)

UNIT IV — AWT & Swing

Q14. What is difference between AWT and Swing?


■ GJU D-23 Q.8 — 14 marks
■ 14 MARKS — WRITE IN FULL DETAIL

■ Answer:
Feature AWT Swing
Package [Link] [Link]
Type Heavyweight (OS native peers) Lightweight (pure Java drawn)
Look & Feel Native OS — varies per platform Consistent across all platforms
Components Button, Frame, TextField JButton, JFrame, JTextField
Rich extras None JTable, JTree, JProgressBar, JTabbedPane
Architecture Peer-based MVC Model-View-Controller
Tooltips No Yes — setToolTipText()
Preferred Legacy only ALL modern apps
JFrame f=new JFrame("Title"); JButton btn=new JButton("OK");
[Link](100,100,100,35); [Link]("Click me!");
[Link](btn); [Link](null); [Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE); [Link](true);

Q15. Differentiate between FlowLayout and BorderLayout.


■ GJU A-22 Q.8(b)

■ Answer:
Feature FlowLayout BorderLayout
Arrangement Left-to-right, wraps to next row 5 fixed zones: N/S/E/W/CENTER
Default for JPanel, Applet JFrame, JDialog
Component size Keeps preferred size Stretches to fill zone
Multiple components/zone Yes — all in one row ONE component per zone
// FlowLayout:
[Link](new FlowLayout([Link],10,10));
// BorderLayout:
[Link](new BorderLayout());
[Link](new JButton("Top"), [Link]);
[Link](new JTextArea("Main"), [Link]);
[Link](new JButton("Bottom"), [Link]);

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 6


PART B — IGNOU MCS-024 | OBJECT ORIENTED TECHNOLOGIES & JAVA
IGNOU · MCS-024 · MCA (Revised) / BCA (Revised) · 3 Hours · 100 Marks · Q1 Compulsory (40 marks) + Any 3 from Q2–Q5 (60 marks)

UNIT I — OOP Fundamentals & Java Basics

Q16. Why is Java platform independent? Explain JVM, JRE, JDK.


■ IGNOU Jun 2024 · Dec 2023 · Dec 2022 — EVERY PAPER
■ COMPULSORY SECTION — EVERY PAPER

■ Answer:
Java is platform-independent because javac compiles to Bytecode (.class) — not native machine code. Any OS with a JVM can run the same .class file —
WORA (Write Once Run Anywhere).
JVM JRE JDK
Contains Bytecode interpreter+JIT+GC JVM + Libraries JRE + javac + tools
For Running bytecode Running Java Developing Java
Has compiler? No No Yes (javac)

Q17. What is OOP? How different from structured programming?


■ IGNOU Dec 2023 · Jun 2022 — RECURRING
■ RECURRING ACROSS MULTIPLE YEARS

■ Answer:
• Encapsulation: data+methods bundled; private fields; access via getters/setters.
• Inheritance: child inherits parent via extends; code reuse; IS-A relationship.
• Polymorphism: overloading=compile-time; overriding=runtime dynamic dispatch.
• Abstraction: hide complexity; show essentials; via abstract class + interface.
Feature Structured (C) OOP (Java)
Data & Functions Separate Bundled in objects (class)
Data Access Global — vulnerable Hidden via encapsulation
Code Reuse Copy-paste functions Inheritance
Real-world model Difficult Natural (Car, Account, Student)
Modularity Low — functions spread globally High — each class self-contained

Advantages of OOP:
• Modularity: each class self-contained — easy to debug and maintain.
• Reusability: inheritance lets child classes reuse parent code automatically.
• Scalability: add new classes without breaking existing code.
• Security: encapsulation hides data — prevents unauthorized access.

Q18. What is 'this' keyword? Explain all uses with examples.


■ IGNOU Jun 2024 Q1(a) · Jun 2023 — 5 marks
■ ASKED IN MULTIPLE RECENT PAPERS

■ Answer:
• Use 1 — disambiguate: [Link]=field; name=parameter. Prevents shadowing.
• Use 2 — constructor chaining: this(args) calls another constructor. Must be first statement.
• Use 3 — method chaining: return this; enables Builder pattern.
• Use 4 — pass current object: [Link](this); passes self as argument.
class Student {
String name; int age;
Student(String name, int age){ [Link]=name; [Link]=age; }
Student(String name){ this(name, 18); } // ctor chaining
Student setName(String n){ [Link]=n; return this; } // method chain
}

Q19. Differentiate between constructor and method.


■ IGNOU Jun 2023 Q1(c) — 5 marks

■ Answer:
Feature Constructor Method
Name Same as class name Any valid identifier
Return type None (not even void) Must have return type or void
Called when Auto on new Explicitly by programmer
Purpose Initialize object state Define object behaviour
Inherited? No Yes (unless private)

Q20. What is a literal in Java? How many types?


■ IGNOU Jun 2024 Q1(f) — 5 marks

■ Answer:

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 7


Type Description Examples
Integer Whole numbers. Decimal/octal(0)/hex(0x)/binary(0b) 42, 052, 0x2A, 0b101, 42L
Floating-point Decimal. double by default; f suffix=float 3.14, 3.14f, 2.5e10
Character Single char in single quotes; Unicode escape 'A', '\n', '\u0041'
String Chars in double quotes; stored in String Pool "Hello", ""
Boolean Only true or false (lowercase) true, false
Null Absent object reference null

UNIT II — Inheritance, Polymorphism & Advanced OOP

Q21. Explain the relationship between inheritance and polymorphism.


■ IGNOU Dec 2022 · Dec 2023 · Jun 2024 — VERY RECURRING
■ ASKED IN 5+ PAPERS

■ Answer:
Inheritance creates IS-A relationship enabling polymorphism. Because Dog IS-A Animal, an Animal reference can hold a Dog object (upcasting). At runtime,
Java dispatches the correct overridden method — dynamic method dispatch.
Animal[] zoo = { new Dog("Rex"), new Cat("Whiskers"), new Parrot("Coco") };
for(Animal a : zoo) {
[Link](); // RUNTIME DISPATCH — correct method chosen per object
}
// Rex barks: Woof! | Whiskers meows: Mrrrow! | Coco squawks: Polly!
■ NOTE: Without inheritance, Animal reference cannot hold Dog/Cat. Inheritance IS what makes polymorphism possible.

Q22. What is method overloading? Rules and examples.


■ IGNOU Dec 2022 · Jun 2022 · Jun 2024 — EVERY PAPER
■ APPEARS IN EVERY PAPER

■ Answer:
Method overloading: same name, different parameter lists. Compile-time (static) polymorphism.
class Calculator {
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
int add(int a, int b, int c) { return a+b+c; }
}
Rule Valid?
Different number of parameters ■ YES
Different parameter types ■ YES
Different parameter order ■ YES
Return type alone different ■ NO — compile error

Q23. What is an abstract class? How to implement polymorphism?


■ IGNOU Jun 2022 · Dec 2023 · Jun 2024 — 4+ papers
■ APPEARS IN 4+ PAPERS

■ Answer:
Abstract class: declared with "abstract" keyword. Cannot instantiate. Contains abstract methods (no body — subclass MUST implement) + concrete methods
(optional to override).
abstract class Employee {
String name; double basicPay;
abstract double calculateAllowance(); // MUST be overridden
double grossPay(){ return basicPay + calculateAllowance(); } // shared
}
class Manager extends Employee {
double calculateAllowance(){ return basicPay * 0.40; } }
class Clerk extends Employee {
double calculateAllowance(){ return basicPay * 0.15; } }
Employee[] staff = { new Manager(...), new Clerk(...) };
for(Employee e: staff) [Link](); // polymorphic dispatch

Q24. Distinguish final, finally and finalize with examples.


■ IGNOU Dec 2022 · Jun 2022 · Jun 2024 — 5+ papers
■ ASKED IN 5+ CONSECUTIVE PAPERS — MEMORISE

■ Answer:
final finally finalize()
Type Keyword Block Method (Object class)
Applies to Variable=constant; method=no override; try-catch block Override in any class
class=no extend
Purpose Prevent modification — immutability Guarantee cleanup code always runs Last cleanup before Garbage Collector destroys
object

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 8


final finally finalize()
Runs when Compile-time enforcement ALWAYS — even if return in try JVM calls before object memory reclaimed
final int MAX=100; // MAX is a constant — cannot reassign
final class ImmutableX{} // cannot subclass
try{ openFile(); } catch(Exception e){ } finally{ closeFile(); } // ALWAYS runs
protected void finalize() throws Throwable { releaseNativeResource(); [Link](); }

Q25. What is a Java applet? How different from application? Applet lifecycle.
■ IGNOU Dec 2022 · Dec 2023 · Jun 2022 — 5+ papers
■ APPEARS IN 5+ PAPERS

■ Answer:
Feature Application Applet
Entry point public static void main() init() method
Execution Standalone via JVM Browser or appletviewer
System access Full Restricted sandbox
Status Standard Deprecated Java 9, removed Java 11
• Lifecycle: init() [once] → start() [each visible] → paint(g) [draw] → stop() [hidden] → destroy() [removed]
■ EXAM TIP: Draw lifecycle flowchart. Write: why no main() in Applet? Because browser calls init() instead.

UNIT III — Exceptions, Threads, I/O & Serialization

Q26. What is an exception? Compare throw vs throws. Custom exception example.


■ IGNOU Jun 2024 · Jun 2022 — 4+ papers
■ APPEARS IN 4+ PAPERS

■ Answer:

Exception Types:
• Checked Exception: detected at COMPILE time. Compiler forces you to handle (try-catch) or declare (throws). Caused by external factors. Examples: IOException,
SQLException, ClassNotFoundException.
• Unchecked Exception (RuntimeException): detected at RUNTIME only. Caused by programming bugs. NOT mandatory to handle. Examples: NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException.
throw throws
What Actually throws an instance Declares method may throw
Where Inside method body Method signature
How many ONE at a time Multiple: throws A, B, C
Mandatory? Used when throwing Mandatory for uncaught checked exceptions
class InsufficientFundsException extends Exception {
double shortfall;
InsufficientFundsException(double n, double a){
super("Need "+n+" but only "+a+" available");
shortfall = n-a;
}
}
void withdraw(double amt) throws InsufficientFundsException {
if(amt>balance) throw new InsufficientFundsException(amt, balance);
}

Q27. Explain multithreading. Thread via Runnable. Lifecycle and priorities.


■ IGNOU Jun 2024 Q4(b) · Dec 2021 — 10 marks
■ 10 MARKS — WRITE IN FULL

■ Answer:
Feature Process Thread
Memory Own address space Shares process heap
Weight Heavy — slow to create Light — fast to create
Communication IPC needed Direct via shared vars
Prefer Runnable over extending Thread (allows extending another class simultaneously).
class Counter implements Runnable {
String name; int limit;
Counter(String n, int l){ name=n; limit=l; }
public void run() {
for(int i=1;i<=limit;i++)
[Link](name+": "+i+"/"+limit);
}
}
Thread t1=new Thread(new Counter("A",5)); [Link](Thread.MAX_PRIORITY);
Thread t2=new Thread(new Counter("B",5)); [Link](Thread.MIN_PRIORITY);
[Link](); [Link]();
• Priorities: MIN=1 | NORM=5 (default) | MAX=10. Priority is a HINT — OS decides actual scheduling.

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 9


Q28. Discuss Garbage Collection — advantages and disadvantages.
■ IGNOU Jun 2024 Q1(h) · Dec 2021 · Jun 2018 — 3+ papers

■ Answer:

What is Garbage Collection?


Garbage Collection (GC) is an automatic memory management mechanism built into the JVM. When an object in the heap is no longer referenced by any
variable, the GC identifies it as garbage and reclaims that memory. Programmers do NOT need to manually free memory (unlike C/C++ where you call
free()/delete).
class GCDemo {
public static void main(String[] args) {
String s = new String("Hello"); // object created in heap
s = null; // reference removed — object now eligible for GC
s = "New"; // old object unreachable — eligible for GC
[Link](); // SUGGEST JVM run GC — not guaranteed!
}
}
Advantages Disadvantages
No manual memory management — no free()/delete needed GC runs at unpredictable times — can cause sudden pauses
Prevents memory leaks — unused objects automatically removed Stop-The-World pauses — app freezes during full GC
Eliminates dangling pointer issues common in C/C++ CPU overhead — GC thread runs consuming resources
Simplifies programming — developer focuses on logic [Link]() is only a suggestion — JVM may ignore it
Increases app reliability — fewer crashes Not suitable for real-time systems (medical, trading)
■ NOTE: Modern JVMs use G1GC, ZGC, Shenandoah GC that minimize pause times. Java 21 generational ZGC pauses < 1ms typically.

Q29. Explain transient and volatile modifiers with examples.


■ IGNOU Jun 2024 Q5(a) · Dec 2022 — 5+ papers
■ SHORT NOTE — 5+ PAPERS

■ Answer:
transient: field is SKIPPED during serialization. Use for passwords, derived values, non-serializable types.
volatile: field always read/written to main memory (not CPU cache). Ensures all threads see latest value.
class UserSession implements Serializable {
String username; // saved
transient String password; // NOT saved — security
transient Connection conn; // NOT saved — not serializable
}
class SharedState {
volatile boolean running = true; // all threads see updates
}
transient volatile
Related to Serialization (disk) Multithreading (CPU cache)
Guarantees Field not persisted Visibility across threads
Does NOT guarantee Threading safety Atomicity (use synchronized)

Q30. Explain object serialization with complete example.


■ IGNOU Jun 2024 Q5(b) · Dec 2022 — 4+ papers
■ APPEARS IN 4+ PAPERS

■ Answer:
Serialization: convert object state to bytes for saving to file or sending over network. Deserialization: reconstruct object from bytes.
• Requirements: class implements Serializable (marker interface). All fields must be Serializable OR marked transient.
class Student implements Serializable {
private static final long serialVersionUID = 2024L;
String name; double cgpa;
transient String password; // NOT saved
}
// Serialize:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("[Link]"));
[Link](new Student("Ram", 8.5, "secret")); [Link]();
// Deserialize:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("[Link]"));
Student s = (Student) [Link](); [Link]();
// [Link] == null (transient was skipped)

UNIT IV — GUI, Networking, JDBC & RMI

Q31. Compare AWT and Swing with examples.


■ IGNOU Jun 2024 · Dec 2023 · Dec 2022 — EVERY PAPER
■ APPEARS IN EVERY PAPER

■ Answer:

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 10


Feature AWT Swing
Package [Link] [Link]
Type Heavyweight — delegates to OS native peers Lightweight — pure Java draws itself
Look & Feel Native OS appearance — varies by platform Consistent across all platforms; customizable
Components Button, TextField, Frame, Dialog JButton, JTextField, JFrame, JDialog
Extra components Very limited JTable, JTree, JProgressBar, JTabbedPane,
JSpinner
Tooltips Not built-in Built-in — setToolTipText()
Double buffering Must implement manually Built-in — no flickering
Architecture Peer model MVC (Model-View-Controller)
Recommended Legacy only ALL modern Java GUI apps
// AWT example:
Frame f=new Frame("AWT"); Button btn=new Button("Click");
[Link](new FlowLayout()); [Link](btn);
[Link](300,200); [Link](true);
// Swing example (same thing, richer):
JFrame jf=new JFrame("Swing"); JButton jbtn=new JButton("Click");
[Link]("Click me!"); [Link]([Link]);
[Link]([Link]);
[Link](new FlowLayout()); [Link](jbtn);
[Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

Q32. Explain Java RMI architecture.


■ IGNOU Dec 2022 · Jun 2022 · Jun 2024 — EVERY PAPER
■ APPEARS IN ALMOST EVERY PAPER

■ Answer:
• 1. Remote Interface: extends [Link]; every method throws RemoteException.
• 2. Remote Object: implements interface + extends UnicastRemoteObject.
• 3. Stub (client proxy): marshals arguments → sends over network.
• 4. Skeleton (server): receives call → unmarshals → invokes → sends result back.
• 5. RMI Registry (port 1099): server [Link](); client [Link]().
// Flow: Client→Stub→[Network]→Skeleton→Remote Object→back
interface Calculator extends Remote { int add(int a,int b) throws RemoteException; }
class CalcImpl extends UnicastRemoteObject implements Calculator {
public CalcImpl() throws RemoteException {}
public int add(int a,int b){ return a+b; }
}
[Link]("//localhost/Calc", new CalcImpl()); // server registers
Calculator c=(Calculator)[Link]("//localhost/Calc"); // client
[Link]([Link](3,4)); // 7 — from remote server!

Q33. What is Java Bean? Discuss its features and conventions.


■ IGNOU Dec 2023 · Dec 2022 · Dec 2021 — 4+ papers
■ ASKED IN 4+ PAPERS

■ Answer:
A Java Bean is a reusable component following conventions so IDEs and frameworks can auto-inspect and configure it.
Convention Rule
1. Public class class must be public
2. No-arg constructor public constructor with no arguments
3. Private fields all properties must be private
4. Getters public getXxx() — returns field value
5. Setters public setXxx(Type val) — sets field value
6. Serializable implements [Link]
public class ProductBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name; private double price;
public ProductBean() {} // no-arg constructor — REQUIRED
public String getName(){ return name; }
public void setName(String n){ name=n; }
public double getPrice(){ return price; }
public void setPrice(double p){ if(p>=0) price=p; }
}

Q34. What is classpath? Explain utility with examples.


■ IGNOU Jun 2024 Q3(b) · Jun 2022 — 4 papers
■ ASKED IN 4 CONSECUTIVE PAPERS

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 11


■ Answer:
CLASSPATH tells javac and JVM where to find .class files and JAR libraries. Without it: "Error: Could not find or load main class".
// Compile and run with libraries:
javac -cp .;lib/[Link];lib/[Link] [Link]
java -cp .;lib/[Link];lib/[Link] MyApp
// Linux/macOS: use colon : instead of semicolon ;
// Wildcard: java -cp .;lib/* MyApp (loads ALL jars in lib/)
• ALWAYS include dot (.) for current directory. -cp flag overrides CLASSPATH env var.

Q35. Stream socket vs Datagram socket.


■ IGNOU Jun 2024 Q1(e) · Jun 2023 · Dec 2022 — 5 marks

■ Answer:

Network Sockets — Overview:


A socket is one endpoint of a two-way communication link between programs running across a network. Java provides socket programming via [Link]
package. Two types exist based on transport protocol.
Feature Stream Socket (TCP) Datagram Socket (UDP)
Protocol TCP — Transmission Control Protocol UDP — User Datagram Protocol
Connection Connection-oriented — must connect first Connectionless — no handshake needed
Reliability 100% reliable — guaranteed delivery Unreliable — packets may be lost
Ordering In-order — packets arrive in sequence Out-of-order — may arrive in any order
Speed Slower — overhead for reliability Faster — minimal overhead
Java classes Socket (client), ServerSocket (server) DatagramSocket, DatagramPacket
Use cases Web, email, SSH, file transfer, databases Video streaming, VoIP, gaming, DNS
// TCP Stream Socket — Server:
ServerSocket server=new ServerSocket(8080);
Socket client=[Link](); // blocks until client connects
BufferedReader in=new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out=new PrintWriter([Link](),true);
[Link]("Server received: "+[Link]());
[Link](); [Link]();
// TCP Stream Socket — Client:
Socket s=new Socket("localhost",8080);
PrintWriter out=new PrintWriter([Link](),true);
[Link]("Hello Server!");
[Link](new BufferedReader(new InputStreamReader([Link]())).readLine());
[Link]();

Q36. Write program to count white spaces, characters, words and full stops in a text file.
■ IGNOU Jun 2024 Q4(a) — 10 marks
■ 10 MARKS PROGRAMMING QUESTION

■ Answer:
import [Link].*;
public class FileAnalyser {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new FileReader("[Link]"));
int chars=0, words=0, spaces=0, dots=0;
String line;
while((line=[Link]())!=null){
chars+=[Link]();
for(char ch:[Link]()){
if(ch==" "||ch=="\t") spaces++;
if(ch==".") dots++;
}
if(![Link]().isEmpty())
words+=[Link]().split("\\s+").length;
}
[Link]();
[Link]("Characters: "+chars);
[Link]("Words : "+words);
[Link]("Spaces : "+spaces);
[Link]("Full Stops: "+dots);
}
}
■ EXAM TIP: For 10 marks: include algorithm + complete code with comments + sample output + mention readLine() returns null at EOF.

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 12


PART C1 — MDU 20MCA21C1 | OOP USING JAVA
Maharshi Dayanand University · Paper: 20MCA21C1 · MCA 1st Sem · 3 Hours · 80 Marks · Q1 compulsory (8×2=16) + Any 4 from 5 units

MDU UNIT I — Java Fundamentals & OOP

Q37. What is the final keyword in Java? Explain all three uses.
■ MDU Dec 2024 Q1(a) — COMPULSORY
■ COMPULSORY Q1 — MDU DEC 2024

■ Answer:
• final variable: constant — cannot be reassigned after initialization.
• final method: cannot be overridden by any subclass.
• final class: cannot be subclassed/extended. e.g., String class is final.
final double PI = 3.14159; // PI=3.0; — COMPILE ERROR
final class String { } // class MySuperString extends String {} — ERROR
class BankAccount {
final void deductFee(){ balance-=150; } // cannot override
}

Q38. What is an object reference variable? How different from primitive?


■ MDU Dec 2024 Q1(b) — COMPULSORY
■ COMPULSORY Q1 — MDU DEC 2024

■ Answer:
Feature Primitive Variable Object Reference Variable
Stores Actual VALUE directly MEMORY ADDRESS of object in Heap
Location Stack Variable on Stack; object on Heap
Default 0, 0.0, false, char:\u0000 (null char) null (points to nothing)
Copying Independent copy BOTH point to SAME object
int a=10; int b=a; a=20; // b is still 10 — independent
int[] arr1={1,2,3}; int[] arr2=arr1;
arr2[0]=99; // arr1[0] is also 99 — same object!
String s=null; [Link](); // NullPointerException!

Q39. Explain data abstraction and encapsulation. How does Java support them?
■ MDU Pattern Q — Unit I OOP Fundamentals

■ Answer:
Abstraction: show WHAT, hide HOW. User calls area() without knowing the formula. Achieved via abstract classes and interfaces.
Encapsulation: bundle data+methods, restrict direct access via private. Access through public getters/setters with validation.
abstract class Shape { abstract double area(); } // abstraction
class Employee { // encapsulation
private double salary; // hidden
public void setSalary(double s){ if(s>=0) salary=s; } // validated
public double getSalary(){ return salary; }
}
Employee e=new Employee();
[Link]=-5000; // COMPILE ERROR — private
[Link](-5000); // setter rejects negative

Q40. Explain Java identifiers — naming rules and conventions.


■ MDU/MU Pattern Q

■ Answer:
• Rules (compile error if violated): Must start with letter/underscore/$. Can contain letters, digits, _, $. No spaces, no special chars, no keywords. Case-sensitive.
• Conventions (best practice): variable/method=camelCase. Class=PascalCase. Constant=ALL_CAPS. Package=[Link].
int age; String _name; double $price; // VALID
int 2count; int my-var; int class; // INVALID — compile error
int studentAge; void calculateSalary(){} // camelCase — variables/methods
class BankAccount{} interface Runnable{} // PascalCase — classes
final int MAX_SIZE=1000; // ALL_CAPS — constants

Q41. What is super keyword? Explain uses with examples.


■ MDU/MU Pattern Q — Inheritance

■ Answer:
• Use 1: Access parent's field when child has same name: [Link] vs [Link].
• Use 2: Call parent's method when child overrides: [Link]() then own drawing.
• Use 3: Call parent's constructor: super(name, age) — MUST be first statement in child constructor.
class Person { String name; int age; Person(String n,int a){name=n;age=a;} }
class Employee extends Person {
double salary;
Employee(String n, int a, double s){

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 13


super(n, a); // calls Person(n,a) — MUST be first line
salary=s;
}
}
■ NOTE: If parent has no no-arg constructor, you MUST call the correct super() explicitly.

Q42. What are wrapper classes? Explain autoboxing and unboxing.


■ MDU/MU Pattern Q — Java API

■ Answer:
Primitive Wrapper Key static method
int Integer [Link]("42"), Integer.MAX_VALUE
double Double [Link]("3.14")
char Character [Link]('5'), isLetter('A')
boolean Boolean [Link]("true")
• Autoboxing: Java auto-converts primitive to wrapper: Integer i = 42; → [Link](42)
• Unboxing: Java auto-converts wrapper to primitive: int y = i + 5; → [Link]() + 5
ArrayList<Integer> list = new ArrayList<>();
[Link](10); // autoboxing — int 10 becomes [Link](10)
int x = [Link](0); // unboxing — [Link]()
Integer n = null; int v = n; // NullPointerException on unboxing null!

MDU UNIT II — Inheritance, Packages & Access Modifiers

Q43. Explain access protection levels in Java.


■ MDU/MU Pattern Q

■ Answer:
Modifier Same Class Same Package Subclass (diff pkg) World
private ■ ■ ■ ■
(default) ■ ■ ■ ■
protected ■ ■ ■ ■
public ■ ■ ■ ■
■ NOTE: Best practice: private fields + public getters/setters. Use protected for methods meant for subclasses.

Q44. What are packages? How to create and use them?


■ MDU/Osmania Pattern Q

■ Answer:
• Package: namespace organizing related classes. Prevents naming conflicts, enables access control, makes code modular.
• Built-in: [Link] (auto-imported), [Link], [Link], [Link], [Link]
// File: com/college/[Link]
package [Link];
public class Student { public String name; public void display(){...} }
// File: [Link]
import [Link];
public class Main {
public static void main(String[] a){
new Student().display();
}
}
// Compile: javac -d . com/college/[Link] then javac [Link]

MDU UNIT III — Collections, Exceptions & Threads

Q45. Write a Java program implementing ArrayList and HashMap from Collections Framework.
■ MDU/Osmania Pattern Q — Collections
■ NEW TOPIC — NOT IN GJU/IGNOU

■ Answer:
Java Collections Framework: unified architecture for storing and manipulating groups of objects.
• List (ordered, duplicates OK): ArrayList, LinkedList | Set (no duplicates): HashSet, TreeSet | Map (key-value): HashMap, TreeMap
ArrayList<String> students = new ArrayList<>();
[Link]("Ram"); [Link]("Seema"); [Link]("Mohan");
[Link](1, "Priya"); // insert at index 1
[Link](students);
for(String s:students) [Link](s);
HashMap<Integer,String> rollMap = new HashMap<>();
[Link](101,"Ram"); [Link](102,"Seema");
[Link]([Link](101)); // Ram
for([Link]<Integer,String> e:[Link]())
[Link]([Link]()+" -> "+[Link]());

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 14


Q46. Explain the five keywords used in exception handling.
■ MDU/Osmania Pattern Q

■ Answer:
Keyword Location Purpose
try Block Wraps risky code that might throw
catch Block after try Handles specific exception type
finally Block after catch Cleanup code — ALWAYS runs
throw Inside method body Explicitly throws an exception instance
throws Method signature Declares checked exceptions method may throw

Q47. Explain multithreading. Thread creation via Runnable interface.


■ MDU Pattern Q — Multithreading

■ Answer:
Extending Thread Implementing Runnable
Can extend another class? ■ No ■ Yes
Preferred? Simple scripts ■ Always preferred
class Producer implements Runnable {
public void run() {
for(String item:items)
[Link]("Produced: "+item);
}
}
Thread t=new Thread(new Producer(), "ProducerThread");
[Link](Thread.MAX_PRIORITY);
[Link]();

MDU UNIT IV — Strings & I/O

Q48. Explain String class methods. Compare String vs StringBuffer vs StringBuilder.


■ MDU Pattern Q — String Handling

■ Answer:

String is IMMUTABLE — StringBuffer/StringBuilder are MUTABLE:


String = immutable: every modification creates a NEW object in memory. StringBuffer = mutable + thread-safe (synchronized). StringBuilder = mutable +
NOT thread-safe (fastest for single thread).
Feature String StringBuffer StringBuilder
Mutable? No — IMMUTABLE Yes — MUTABLE Yes — MUTABLE
Thread-safe? Yes (immutable) Yes (synchronized) No — fastest
Use case Fixed text Multi-thread ops Single-thread ops

Method Description Example


length() Count characters "Hello".length() → 5
charAt(i) Char at index i "Hello".charAt(1) → 'e'
substring(s,e) Substring s to e-1 "Hello".substring(1,4) → "ell"
indexOf(str) First position; -1=not found "Hello".indexOf("ll") → 2
equals(s) Content comparison "Hi".equals("hi") → false
toUpperCase() To uppercase "hello".toUpperCase() → "HELLO"
trim() Remove leading/trailing spaces " hi ".trim() → "hi"
split(regex) Split to array "a,b".split(",") → ["a","b"]
■ NOTE: ALWAYS use equals() to compare String content. NEVER use == — it compares memory addresses, not content.

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 15


PART C2 — OSMANIA PCC103 | OOP USING JAVA
Nizam College (Autonomous) — Osmania University, Hyderabad · PCC103 · MCA I Sem · CIE 30 + SEE 70 = 100 marks · 5 Units · 99-question bank

UNIT I — OOP Concepts & Java Fundamentals

Q49. Discuss core OOP concepts and advantages of OO Development.


■ Osmania Q1 & Q2 — Unit I Assignment Questions
■ OSMANIA UNIT I — CORE THEORY

■ Answer:
• Encapsulation: data+code in one class; private fields; controlled access via public methods.
• Inheritance: child class inherits parent members (extends); IS-A; promotes code reuse.
• Polymorphism: overloading=compile-time; overriding=runtime. One interface, many forms.
• Abstraction: abstract class + interface; hide implementation; expose only essentials.
• Advantages: Modularity, Reusability (inheritance), Scalability, Data security (private), Natural real-world modeling, Collaborative development.

Q50. Give overview of Java arrays. Demonstrate 1D and 2D array programs.


■ Osmania Q5, Q6, Q7 — Unit I

■ Answer:

What is an Array?
An array is a fixed-size, ordered collection of elements of the SAME data type. Size is set at creation and cannot change later. Arrays are objects in Java —
stored on Heap. Elements accessed via index (0-based). The .length property gives the array size.
// 1D Array:
int[] scores = {85,92,78,96,88};
int max=scores[0];
for(int s:scores) if(s>max) max=s;
[Link]("Max: "+max); // 96
// 2D Array (Matrix):
int[][] m = {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++) [Link]("%3d",m[i][j]);
[Link]();
}

UNIT II — I/O Streams, Strings & Exception Handling

Q51. Explain String class and methods. Demonstrate 5 key methods.


■ Osmania Q41, Q42 — Unit II

■ Answer:
String: immutable class in [Link] (auto-imported). Stored in String Pool — identical literals share same object.
String s = "Hello World Java";
[Link]([Link]()); // 16
[Link]([Link]()); // HELLO WORLD JAVA
[Link]([Link](6,11)); // World
[Link]([Link]("World")); // 6
String[] words = [Link](" ");
[Link]([Link]); // 3
// == vs equals() — CRITICAL DIFFERENCE:
String a="Hello"; String b=new String("Hello");
[Link](a==b); // false — different objects
[Link]([Link](b));// true — same content

UNIT III — Collections Framework (UNIQUE TO OSMANIA)

Q52. Explain Collections hierarchy. Demonstrate Iterator and ListIterator.


■ Osmania Q49,Q50,Q52,Q70,Q71 — Unit III
■ UNIQUE TO OSMANIA — NOT IN GJU/IGNOU

■ Answer:
• Iterable → Collection → List (ordered, duplicates): ArrayList, LinkedList, Vector
• Iterable → Collection → Set (no duplicates): HashSet, TreeSet, LinkedHashSet
• Iterable → Collection → Queue (FIFO): PriorityQueue, ArrayDeque
• Map (key-value, separate hierarchy): HashMap, LinkedHashMap, TreeMap
ArrayList<String> list = new ArrayList<>();
[Link]("Java"); [Link]("DBMS"); [Link]("OS");
// Iterator — forward only, safe removal:
Iterator<String> it = [Link]();
while([Link]()){ String s=[Link](); if([Link]("OS")) [Link](); }
// ListIterator — bidirectional:
ListIterator<String> lit = [Link]();
while([Link]()) [Link]([Link]()+": "+[Link]());

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 16


while([Link]()) [Link]([Link]()); // reverse
Feature Iterator ListIterator
Direction Forward only Both forward AND backward
Works with Any Collection List only
Can add/replace? No Yes — add()/set()

Q53. Explain TreeSet and HashMap. What is Comparator?


■ Osmania Q66,Q68,Q73,Q76 — Unit III
■ UNIQUE TO OSMANIA — MUST KNOW

■ Answer:
// TreeSet — auto-sorted, no duplicates:
TreeSet<Integer> marks=new TreeSet<>();
[Link](85); [Link](92); [Link](78); [Link](85); // dup ignored
[Link](marks); // [78, 85, 92] — sorted
// Comparator — custom sorting:
ArrayList<Student> students = ...;
[Link]((s1,s2) -> [Link] - [Link]); // sort by marks ascending
[Link]((s1,s2) -> [Link]([Link])); // sort by name

UNIT IV — AWT Controls, Events & Layout Managers

Q54. Explain TextField and TextArea controls with event handling.


■ Osmania Q73,Q74 — Unit IV
■ UNIQUE — AWT CONTROLS DETAIL

■ Answer:
class TextDemo extends Frame implements ActionListener {
TextField nameFld = new TextField(20);
Label result = new Label("Fill form");
Button btn = new Button("Submit");
TextDemo(){
setLayout(new FlowLayout()); add(nameFld); add(btn); add(result);
[Link](this); setSize(300,120); setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Hello "+[Link]());
}
}
Feature TextField TextArea
Lines Single line Multiple lines
Common use Name, search Comments, feedback

Q55. Explain GridBagLayout with example.


■ Osmania Q80 — Unit IV
■ UNIQUE TOPIC — ONLY IN OSMANIA

■ Answer:
GridBagLayout: most flexible layout. Each component has its own GridBagConstraints controlling position, span, fill and alignment.
• Key constraints: gridx/gridy=position | gridwidth/gridheight=span | fill=NONE/HORIZONTAL/VERTICAL/BOTH | anchor=CENTER/WEST/EAST |
weightx/weighty=resize proportion | insets=padding
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
setLayout(gbl); [Link]=new Insets(5,5,5,5);
[Link]=0; [Link]=0; add(new Label("Name:"), gbc);
[Link]=1; [Link]=2; [Link]=[Link];
[Link]=1.0; add(new TextField(20), gbc);

UNIT V — Swing, Networking & Image Processing

Q56. Write TCP client-server program with bidirectional communication.


■ Osmania Q94,Q95,Q96 — Unit V
■ UNIQUE TO OSMANIA — NETWORKING

■ Answer:
// SERVER:
ServerSocket server=new ServerSocket(9999);
Socket client=[Link]();
BufferedReader in=new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out=new PrintWriter([Link](),true);
String msg=[Link](); [Link]("Client: "+msg);
[Link]("Server received: "+msg);
[Link](); [Link]();

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 17


// CLIENT:
Socket s=new Socket("localhost",9999);
PrintWriter out=new PrintWriter([Link](),true);
BufferedReader in=new BufferedReader(new InputStreamReader([Link]()));
[Link]("Hello Server!");
[Link]([Link]()); // Server received: Hello Server!
[Link]();

Q57. Write a program to convert an image to grayscale.


■ Osmania Q99 — Unit V
■ UNIQUE TO OSMANIA — IMAGE PROCESSING

■ Answer:
Grayscale formula (ITU-R BT.601): gray = 0.299R + 0.587G + 0.114B. Green contributes most because human eyes are most sensitive to green.
import [Link].*; import [Link].*; import [Link].*; import [Link].*;
public class GrayscaleConverter {
public static void main(String[] a) throws IOException {
BufferedImage img=[Link](new File("[Link]"));
int w=[Link](), h=[Link]();
BufferedImage gray=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY);
for(int y=0;y<h;y++) for(int x=0;x<w;x++){
Color px=new Color([Link](x,y));
int g=(int)(0.299*[Link]()+0.587*[Link]()+0.114*[Link]());
[Link](x,y,new Color(g,g,g).getRGB());
}
[Link](gray,"jpg",new File("[Link]"));
[Link]("Converted: "+w+"x"+h+" pixels");
}
}

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 18


PART C3 — MUMBAI UNIVERSITY MCA11 | OOP WITH JAVA
University of Mumbai · MCA Semester I · Code: MCA11 · 3 Hours · 80 Marks · Part-I: Q1 (10×2=20) · Part-II: Q2 (8×6=48) · Part-III: Any 2 of Q3-Q6 (2×6=12)

PART I — Short Questions (2 marks each)

Q58. Distinguish between Data Abstraction and Data Encapsulation.


■ Mumbai Q1(b) Pattern — Part I, 2 marks

■ Answer:
Feature Abstraction Encapsulation
Meaning Show essential; hide implementation Bundle data+methods; restrict access
Mechanism abstract class, interface private fields + getters/setters
Level Design level concept Implementation level technique

Q59. Is Java a platform-neutral language? Justify.


■ Mumbai Q1(c) Pattern — Part I

■ Answer:
YES. Java is platform-neutral because:
• javac compiles .java to .class bytecode — not native machine code.
• The SAME .class file runs on any OS that has a JVM installed.
• JVM translates bytecode to native instructions specific to each OS+CPU.
This is WORA: Developer writes on Windows → .class file → runs on Linux/macOS/Android unchanged.

Q60. State difference between instance variables and class (static) variables.
■ Mumbai Q1(f) Pattern

■ Answer:
Feature Instance Variable Class Variable (static)
Belongs to Each individual object The CLASS itself
Memory Separate copy per object ONE copy shared by ALL objects
Created when Object created with new Class loaded by JVM
Access [Link] [Link]

Q61. Wrapper classes? Difference between overriding and overloading.


■ Mumbai Q1(h)(i) Pattern

■ Answer:
Wrapper classes: int→Integer, double→Double, char→Character, boolean→Boolean. Used when objects needed (ArrayList, generics). Provide utility:
[Link](), [Link]().
Feature Overloading Overriding
Location Same class Subclass redefines parent method
Parameters MUST differ MUST be identical
Polymorphism Compile-time (static) Runtime (dynamic)

Q62. Explain unchecked and checked exceptions.


■ Mumbai Q1(j) Pattern

■ Answer:
Feature Checked Exception Unchecked (RuntimeException)
Detected at Compile time Runtime
Must handle? YES — or declare throws No — optional
Caused by External resources (files, DB) Programming bugs (null, bad index)
Examples IOException, SQLException NullPointerException, ArrayIndexOutOfBounds

PART II — Medium Questions (6 marks each)

Q63. Describe access protection levels in Java with package boundary example.
■ Mumbai Q2(a) Pattern — Part II, 6 marks
■ PART II — 6 MARKS

■ Answer:
Modifier Same Class Same Package Subclass (diff pkg) World
private ■ ■ ■ ■
(default) ■ ■ ■ ■
protected ■ ■ ■ ■
public ■ ■ ■ ■
package [Link];
public class Parent {
private int a=1; // COMPILE ERROR if accessed outside this class
int b=2; // COMPILE ERROR if accessed from different package

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 19


protected int c=3; // OK in subclass even from different package
public int d=4; // OK everywhere
}
package [Link];
public class Child extends Parent {
void test(){
[Link](a); // COMPILE ERROR — private
[Link](b); // COMPILE ERROR — default, different package
[Link](c); // OK — protected accessible in subclass
[Link](d); // OK — public accessible everywhere
}
}

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 20


QUICK REVISION — ALL 5 UNIVERSITIES · KEY ONE-LINERS
Uni Topic Key One-Liner — Memorise This
BOTH×5 JVM/Bytecode javac→.class→JVM interprets→any OS. WORA. JDK⊃JRE⊃JVM.

BOTH×5 OOP (EIPA) Encapsulation·Inheritance·Polymorphism·Abstraction. Core 4 pillars.

BOTH×5 Inheritance extends; IS-A; Single/Multi/Hierarchical; Multiple via interface only.

BOTH×5 Polymorphism Overloading=compile-time(diff params). Overriding=runtime(dynamic dispatch).

BOTH×5 Exception throw=create+throw; throws=declare. Checked=compile; Unchecked=runtime.

BOTH×5 Threads Thread or Runnable. ALWAYS start() not run(). MIN=1 NORM=5 MAX=10.

BOTH×5 Abstract Cannot instantiate; abstract methods MUST be overridden; can have concrete.

BOTH×5 Interface Contract; public static final fields; multiple impl; Java 8 adds default.

BOTH×5 AWT vs Swing AWT=heavyweight/OS-native. Swing=lightweight/pure-Java/rich. Swing preferred.

BOTH×5 String String=immutable. StringBuffer=mutable+sync. StringBuilder=mutable+fast.

GJU+IGNOU final/finally final=immutable; finally=ALWAYS runs; finalize()=GC calls before destruction.

GJU+IGNOU Applet init→start→paint→stop→destroy. No main(). Browser controls. Deprecated Java 9.

GJU+IGNOU GC Auto memory. [Link]()=suggestion. finalize()=before destruction.

GJU Singleton private ctor + private static instance + synchronized getInstance() → ONE object.

GJU Diamond Prob Multiple class inheritance banned. Interfaces solve via [Link]().

GJU Layout FlowLayout=left-right-wrap(JPanel). BorderLayout=5 zones N/S/E/W/CENTER(JFrame).

IGNOU Java Bean Public class+no-arg ctor+private fields+getters/setters+Serializable. ALL 6 needed.

IGNOU Classpath Tells JVM where .class/JARs are. Include . (dot). -cp overrides env variable.

IGNOU transient Skips field during serialization. Passwords, derived values, non-Serializable types.

IGNOU volatile Read/write to main memory (not CPU cache). Visibility across threads guaranteed.

IGNOU RMI Remote Interface→UnicastRemoteObject→Registry→Stub(client)/Skeleton(server).

MDU final keyword final var=constant; final method=no override; final class=no extend (e.g. String).

MDU Reference var Stores memory address of Heap object. Default=null. Copying copies reference.

MDU super [Link]/method=parent access. super()=parent ctor — MUST be first statement.

MDU Wrapper int→Integer, double→Double. Autoboxing: int→Integer auto. Unboxing: Integer→int auto.

MDU Access Mods private private<default<protected<publiclt; default private<default<protected<publiclt; protected


private<default<protected<publiclt; public. private=class only. public=everywhere.

MDU+OU Collections List=ordered+duplicates(ArrayList). Set=no-dups(HashSet,TreeSet). Map=key-val(HashMap).

Osmania Iterator [Link]()/next()/remove(). ListIterator adds: hasPrevious/previous/add/set.

Osmania Comparator Custom sort: [Link]((a,b)->[Link]). Comparable: implements compareTo().

Osmania GridBagLayout gridx/gridy=position. gridwidth=span. fill=HORIZONTAL. weightx=resize share.

Osmania Image Gray gray=0.299R+0.587G+0.114B. BufferedImage.TYPE_BYTE_GRAY. [Link]/write.

Mumbai Platform Neut. javac→.class(any OS). JVM translates to native on each OS. WORA principle.

Mumbai Instance vs Static Instance=separate copy per object. Static=ONE copy shared(class var). [Link].

Mumbai Checked vs Unch. Checked=compile-time(IOException). Unchecked=runtime(NPE). Checked MUST be handled.

END OF COMPLETE NOTES — GJU · IGNOU · MDU · OSMANIA · MUMBAI | Best of luck! ■

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 21


PART D — IMPORTANT PROBABLE QUESTIONS | ALL 5 UNIVERSITIES
High-frequency topics identified from past papers of GJU, IGNOU, MDU, Osmania and Mumbai. These questions are highly likely to appear in upcoming exams.

CATEGORY 1 — Constructor & Method Concepts

Q64. What is constructor overloading? Explain with a complete example.


■ GJU D-23 | IGNOU Jun-24 | MDU | Mumbai — VERY HIGH PROBABILITY
■ ASKED IN ALMOST EVERY PAPER

■ Answer:
Constructor Overloading: defining multiple constructors in the same class with different parameter lists. Java uses the parameter types to decide which
constructor to call at object creation.
Rules: same name as class, no return type, different parameter lists (type/number/order). Use this() to chain constructors — must be first statement.
class Rectangle {
double length, width;
Rectangle() { // no-arg constructor
length = 1.0; width = 1.0;
}
Rectangle(double side) { // square constructor
length = side; width = side;
}
Rectangle(double l, double w) { // full constructor
length = l; width = w;
}
double area() { return length * width; }
}
Rectangle r1 = new Rectangle(); // calls no-arg: 1x1
Rectangle r2 = new Rectangle(5); // calls single: 5x5
Rectangle r3 = new Rectangle(4, 6); // calls full: 4x6
[Link]([Link]()); // 1.0
[Link]([Link]()); // 25.0
[Link]([Link]()); // 24.0
■ EXAM TIP: Constructor chaining with this(): Rectangle(double side){ this(side, side); } — must be FIRST line.

Q65. Explain pass by value in Java. Is Java pass by value or pass by reference?
■ IGNOU | MDU | Mumbai Pattern — HIGH PROBABILITY
■ COMMON TRICKY QUESTION

■ Answer:
Java is ALWAYS pass by value — there is no pass by reference in Java. However the behavior differs:
• Primitive types: a COPY of the value is passed. Changes inside method do NOT affect original.
• Object references: a COPY of the REFERENCE (memory address) is passed. Method can modify the object fields (same heap object), but cannot make the original
variable point to a different object.
static void changeInt(int x) { x = 99; } // copy — original unchanged
static void changeName(Student s) {
[Link] = "Updated"; // modifies SAME heap object — original sees change
s = new Student("New"); // ONLY changes local copy of reference — original unchanged
}
int num = 10;
changeInt(num);
[Link](num); // 10 — UNCHANGED (primitive copy)
Student st = new Student("Ram");
changeName(st);
[Link]([Link]); // "Updated" — field changed via same object
// st still points to original object — not to "New"
■ NOTE: "Pass by value of the reference" is the accurate term. Java copies the reference value (address), not the object itself.

Q66. Explain Heap and Stack memory in Java with diagram.


■ IGNOU | MDU | Osmania Pattern — HIGH PROBABILITY
■ MEMORY MODEL — ASKED IN ALL UNIVERSITIES

■ Answer:
Feature Stack Heap
What stored Method call frames, local variables, references All objects created with new, instance variables
Memory size Small (fixed per thread) Large (shared by all threads)
Access speed Very fast (LIFO) Slower (dynamic allocation)
Lifetime Until method returns Until Garbage Collector removes it
Thread Each thread has its OWN stack One shared heap for ALL threads
Error StackOverflowError (deep recursion) OutOfMemoryError (too many objects)
public static void main(String[] args) {

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 22


int age = 25; // STACK: primitive stored directly
String name = "Ram"; // STACK: reference; "Ram" in String Pool (Heap)
Student s = new Student("Ram", 25); // STACK: ref s; object in HEAP
} // s, age, name popped off stack; Student object eligible for GC
■ EXAM TIP: Draw stack-heap diagram. Show: local var on stack, object on heap, reference arrow from stack to heap.

CATEGORY 2 — Thread Synchronization

Q67. What is synchronization in Java? Explain synchronized keyword with example.


■ GJU | IGNOU | MDU | Osmania — VERY HIGH PROBABILITY
■ ASKED IN EVERY MULTITHREADING QUESTION

■ Answer:
Synchronization: a mechanism that ensures only ONE thread can access a critical section (shared resource) at a time. Prevents Race Conditions — incorrect
results when multiple threads read/write shared data simultaneously.
synchronized keyword can be applied to: (1) instance methods, (2) static methods, (3) code blocks. When a thread enters a synchronized method/block it
acquires a LOCK (monitor) on the object. Other threads wait until the lock is released.
class BankAccount {
private double balance = 10000;
// synchronized method — only ONE thread at a time
public synchronized void withdraw(double amt) {
if (balance >= amt) {
[Link]([Link]().getName()+" withdrawing "+amt);
balance -= amt;
[Link]("Remaining: " + balance);
} else {
[Link]("Insufficient funds");
}
}
}
BankAccount acc = new BankAccount();
Thread t1 = new Thread(() -> [Link](6000), "Thread-A");
Thread t2 = new Thread(() -> [Link](6000), "Thread-B");
[Link](); [Link]();
// WITHOUT synchronized: both might see balance=10000 and both withdraw 6000
// WITH synchronized: Thread-A withdraws, then Thread-B sees balance=4000 → refused
■ NOTE: synchronized block: synchronized(this){ ... } — finer control, locks only critical section not entire method.

Q68. What is Deadlock? How to prevent it?


■ IGNOU | MDU | Osmania Pattern — HIGH PROBABILITY
■ COMMON THEORY + DIAGRAM QUESTION

■ Answer:
Deadlock: a situation where two or more threads are PERMANENTLY BLOCKED, each waiting for a lock held by the other. No thread can proceed —
application hangs.
4 necessary conditions (Coffman): (1) Mutual Exclusion — resource held exclusively. (2) Hold and Wait — thread holds one lock and waits for another. (3)
No Preemption — locks cannot be forcibly taken. (4) Circular Wait — T1 waits for T2, T2 waits for T1.
// DEADLOCK EXAMPLE:
Object lock1 = new Object(), lock2 = new Object();
Thread t1 = new Thread(() -> {
synchronized(lock1) { // T1 acquires lock1
[Link](100);
synchronized(lock2) { /* ... */ } // T1 waits for lock2 (held by T2)
}
});
Thread t2 = new Thread(() -> {
synchronized(lock2) { // T2 acquires lock2
[Link](100);
synchronized(lock1) { /* ... */ } // T2 waits for lock1 (held by T1)
}
});
// T1 holds lock1, waits lock2. T2 holds lock2, waits lock1. DEADLOCK!

Prevention strategies:
• Lock ordering: always acquire locks in same fixed order (e.g. always lock1 before lock2).
• Try-lock with timeout: use [Link](timeout) — gives up if cannot acquire.
• Avoid nested locks: do not acquire a second lock while holding one.

CATEGORY 3 — String Pool & Memory

Q69. Explain String Pool in Java. What is intern() method?


■ IGNOU | MDU | Mumbai Pattern — HIGH PROBABILITY
■ IMPORTANT MEMORY CONCEPT

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 23


■ Answer:
String Pool (String Constant Pool / String Intern Pool): a special area in Java Heap where the JVM stores unique string literals. When you write "Hello" twice,
both variables point to the SAME object in the pool — memory efficient.
String s1 = "Hello"; // stored in String Pool
String s2 = "Hello"; // reuses SAME object from pool
String s3 = new String("Hello"); // creates NEW object in regular Heap (NOT pool)
[Link](s1 == s2); // true — same pool object
[Link](s1 == s3); // false — s3 is in heap, not pool
[Link]([Link](s3)); // true — same content
// intern() — forces a string to be placed in pool:
String s4 = [Link](); // returns pool reference
[Link](s1 == s4); // true — both now point to pool object
Created with Location In Pool?
"Hello" literal String Pool (Heap) Yes — shared
new String("Hello") Regular Heap No — unique object
[Link]() String Pool (Heap) Yes — added to pool
■ NOTE: String pool is possible ONLY because String is IMMUTABLE. If strings could change, sharing would be dangerous.

Q70. Compare ArrayList vs LinkedList vs Vector.


■ MDU | Osmania | Mumbai Pattern — HIGH PROBABILITY
■ COLLECTIONS COMPARISON

■ Answer:
Feature ArrayList LinkedList Vector
Internal structure Dynamic array Doubly-linked list Dynamic array
Random access O(1) — fast by index O(n) — must traverse O(1) — fast by
index
Insert/Delete (middle) O(n) — shift elements O(1) — just relink nodes O(n) — shift
elements
Insert (end) O(1) amortized O(1) O(1) amortized
Thread-safe? No — use [Link]() No Yes —
synchronized (slow)
Null allowed? Yes Yes Yes
Iterator Fail-fast Fail-fast Fail-safe
(Enumeration)
Prefer when Frequent reads/access Frequent insert/delete Legacy — avoid
(use ArrayList)
ArrayList<String> al = new ArrayList<>(); // most common
LinkedList<String> ll = new LinkedList<>(); // use as queue/deque too
[Link]("A"); [Link]("Z"); // Deque operations
[Link]("X"); // stack/queue operations

CATEGORY 4 — JDBC (Database Connectivity)

Q71. What is JDBC? Write complete steps to connect Java to a database.


■ IGNOU MCS-024 | MDU | Osmania | Mumbai — VERY HIGH PROBABILITY
■ ■ MUST KNOW FOR MCA — EVERY UNIVERSITY

■ Answer:
JDBC (Java Database Connectivity): Java API providing methods to connect to databases (MySQL, Oracle, PostgreSQL etc.), execute SQL queries, and
retrieve results. Part of [Link] package.
7 Steps of JDBC:
• Step 1 — Import: import [Link].*;
• Step 2 — Register Driver: [Link]("[Link]") — loads the driver class.
• Step 3 — Create Connection: [Link](url, user, password).
• Step 4 — Create Statement: [Link]() or [Link](sql).
• Step 5 — Execute Query: [Link](sql) for SELECT; [Link](sql) for INSERT/UPDATE/DELETE.
• Step 6 — Process ResultSet: while([Link]()) { [Link]("name"); }
• Step 7 — Close: [Link](); [Link](); [Link](); — ALWAYS in finally or try-with-resources.
import [Link].*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root", pass = "password";
try (Connection con = [Link](url, user, pass);
Statement stmt = [Link]()) {
// INSERT
[Link]("INSERT INTO students VALUES(1,"Ram",8.5)");
// SELECT
ResultSet rs = [Link]("SELECT * FROM students");

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 24


while ([Link]()) {
[Link]([Link](1) + " " +
[Link]("name") + " " +
[Link]("cgpa"));
}
} catch (SQLException e) {
[Link]();
}
}
}
■ NOTE: PreparedStatement is preferred over Statement: prevents SQL injection. PreparedStatement ps = [Link]("INSERT INTO students VALUES(?,?,?)");
[Link](1,2); [Link](2,"Seema"); [Link](3,9.1); [Link]();
■ EXAM TIP: Write: Statement vs PreparedStatement. Statement = SQL as string (injection risk). PreparedStatement = precompiled with ? placeholders (safe, faster for
repeated queries).

CATEGORY 5 — Nested Classes & Anonymous Classes

Q72. Explain different types of nested classes in Java with examples.


■ IGNOU | MDU | Osmania Pattern — HIGH PROBABILITY
■ IMPORTANT OOP CONCEPT

■ Answer:
Type Description Access to outer class When to use
Static Nested static class inside another class. No outer instance Only static members Helper class not needing outer state
needed.
Inner (Non-static) Non-static class inside another. Needs outer All (including private) Closely tied to outer class
instance.
Local Class defined inside a method. Visible only in that Effectively final vars One-off implementation
method.
Anonymous Class without a name, defined and instantiated in Enclosing scope vars Single-use interface/abstract impl
one expression.
// Anonymous class — most common in exams:
interface Greeting { void greet(String name); }
Greeting formal = new Greeting() { // anonymous class
public void greet(String name) {
[Link]("Good morning, " + name);
}
};
[Link]("Professor"); // Good morning, Professor
// Anonymous class for event handling (very common in AWT/Swing):
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

CATEGORY 6 — Java 8 Features

Q73. What are Lambda Expressions in Java 8? Explain with examples.


■ MDU | Mumbai | Osmania — MEDIUM-HIGH PROBABILITY
■ MODERN JAVA FEATURE

■ Answer:
Lambda Expression: a short anonymous function. Syntax: (parameters) -> expression. Can be used wherever a functional interface (interface with ONE
abstract method) is expected. Makes code more concise.
Functional Interface: has exactly one abstract method. Examples: Runnable, Comparator, ActionListener, Predicate, Consumer, Function.
// Old way (anonymous class):
Runnable r = new Runnable() {
public void run() { [Link]("Old way"); }
};
// Lambda way:
Runnable r2 = () -> [Link]("Lambda way");
new Thread(r2).start();
// Lambda with Comparator:
ArrayList<String> names = new ArrayList<>([Link]("Zara","Anna","Bob"));
[Link]((a, b) -> [Link](b)); // sort ascending
[Link]((a, b) -> [Link](a)); // sort descending
// Lambda with [Link]:
[Link](name -> [Link]("Hello " + name));
// Method reference (shorthand lambda):
[Link]([Link]::println); // same as n -> [Link](n)
■ EXAM TIP: Lambda = anonymous function for functional interfaces. Key: removes boilerplate of anonymous class. Arrow (->) separates parameters from body.

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 25


Q74. What are Generic classes in Java? Why are they used?
■ IGNOU | MDU | Osmania Pattern — HIGH PROBABILITY
■ TYPE SAFETY CONCEPT

■ Answer:
Generics: allow classes, interfaces and methods to operate on objects of any type while providing compile-time type safety. Eliminates the need for type
casting and catches ClassCastException errors at compile time instead of runtime.
// Without generics (unsafe):
ArrayList list = new ArrayList();
[Link]("Hello"); [Link](42); // compiles OK
String s = (String) [Link](1); // ClassCastException at RUNTIME!
// With generics (type-safe):
ArrayList<String> safeList = new ArrayList<String>();
[Link]("Hello");
// [Link](42); // COMPILE ERROR — caught at compile time!
String s2 = [Link](0); // no cast needed
// Generic class definition:
class Pair<T, U> {
private T first;
private U second;
public Pair(T f, U s) { first=f; second=s; }
public T getFirst() { return first; }
public U getSecond() { return second; }
}
Pair<String, Integer> p = new Pair<>("Score", 95);
[Link]([Link]() + ": " + [Link]()); // Score: 95
■ NOTE: T, U, E, K, V are common type parameter names by convention (Type, Use, Element, Key, Value). The actual type is supplied at object creation.

CATEGORY 7 — Comparable vs Comparator & Collections Sorting

Q75. Differentiate Comparable and Comparator. Write programs for both.


■ MDU | Osmania | Mumbai — HIGH PROBABILITY
■ COLLECTIONS SORTING — COMMON EXAM QUESTION

■ Answer:
Feature Comparable Comparator
Package [Link] [Link]
Method compareTo(Object o) — 1 method compare(Object o1, Object o2) — external
Modifies class? YES — class must implement it NO — separate class or lambda
Natural/Custom Natural ordering (default) Custom ordering (flexible)
Use when Class has ONE natural order (Student by rollNo) Need MULTIPLE sort criteria
// Comparable — natural order (by rollNo):
class Student implements Comparable<Student> {
int rollNo; String name; double marks;
public int compareTo(Student other) {
return [Link] - [Link]; // ascending by rollNo
}
}
[Link](students); // uses compareTo automatically
// Comparator — multiple custom sorts:
Comparator<Student> byName = (s1,s2) -> [Link]([Link]);
Comparator<Student> byMarks = (s1,s2) -> [Link]([Link], [Link]);
[Link](byName); // sort by name A-Z
[Link](byMarks); // sort by marks high to low

CATEGORY 8 — try-with-resources & Exception Handling (Java 7)

Q76. What is try-with-resources in Java 7? Why is it better than finally?


■ IGNOU | MDU | Mumbai Pattern — HIGH PROBABILITY
■ JAVA 7 IMPORTANT FEATURE

■ Answer:
try-with-resources (Java 7+): automatically closes resources (files, connections, streams) when try block exits — whether normally or via exception. Resource
class must implement AutoCloseable/Closeable interface.
// OLD WAY (Java 6 and earlier) — verbose, error-prone:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("[Link]"));
String line = [Link]();
[Link](line);
} catch (IOException e) {

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 26


[Link]();
} finally {
if (br != null) try { [Link](); } catch (IOException e) {} // ugly!
}
// NEW WAY (Java 7) — try-with-resources:
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null)
[Link](line);
} catch (IOException e) {
[Link]();
}
// [Link]() is called AUTOMATICALLY — no finally needed!
// Multiple resources — all auto-closed in REVERSE order:
try (Connection con = [Link](url, user, pass);
Statement stmt = [Link]()) {
ResultSet rs = [Link]("SELECT * FROM students");
} // stmt closed first, then con closed
■ EXAM TIP: Advantage over finally: (1) cleaner code, (2) suppressed exceptions handled properly, (3) multiple resources on ONE try line, (4) no risk of forgetting
close().

CATEGORY 9 — Event Handling in Java GUI

Q77. Explain event handling in Java AWT. Write program with ActionListener and MouseListener.
■ GJU | IGNOU | Osmania Pattern — HIGH PROBABILITY
■ GUI PROGRAMMING — IMPORTANT

■ Answer:
Event: user action (click, keystroke, mouse movement). Event Source: component generating event (Button, TextField). Event Listener: interface with
callback methods called when event fires. Event Object: carries event info (ActionEvent, MouseEvent).
Steps: (1) Create component. (2) Create listener object. (3) Register: [Link](listener). (4) Implement callback method.
import [Link].*; import [Link].*;
class EventDemo extends Frame implements ActionListener, MouseListener {
Button btn = new Button("Click Me");
Label lbl = new Label("Events will show here");
EventDemo() {
setLayout(new FlowLayout());
add(btn); add(lbl);
[Link](this); // register ActionListener
addMouseListener(this); // register MouseListener on frame
setSize(350, 150); setVisible(true);
}
// ActionListener — button click:
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked! Source: " + [Link]());
}
// MouseListener — 5 methods (must implement all 5):
public void mouseClicked(MouseEvent e) { [Link]("Mouse clicked at "+[Link]()+","+[Link]()); }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { [Link]("Mouse over!"); }
public void mouseExited(MouseEvent e) { [Link]("Click Me"); }
}
■ NOTE: MouseAdapter class: extend instead of implement MouseListener. Override ONLY methods you need — others have empty implementations already.

CATEGORY 10 — Enum, HashMap Deep Dive & instanceof

Q78. What is Enum in Java? How is it different from a class?


■ IGNOU | MDU | Mumbai Pattern — MEDIUM-HIGH
■ SHORT QUESTION — FREQUENTLY ASKED

■ Answer:
Enum (Enumeration): a special Java class representing a group of named constants. More type-safe than using int constants (like 1,2,3 for seasons). Each
enum constant is an instance of the enum class.
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() { return this==SATURDAY || this==SUNDAY; }
}
Day today = [Link];
[Link](today); // WEDNESDAY
[Link]([Link]()); // 2 (0-based index)
[Link]([Link]()); // "WEDNESDAY"

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 27


[Link]([Link]()); // false
// switch with enum:
switch (today) {
case SATURDAY: case SUNDAY: [Link]("Weekend!"); break;
default: [Link]("Weekday — study Java!");
}
Feature Enum Class
Can have methods? Yes Yes
Can be instantiated with new? No — fixed constants only Yes
Implicitly extends [Link] [Link]
Best use Fixed set of constants General-purpose

Q79. Compare HashMap, Hashtable, LinkedHashMap and TreeMap.


■ MDU | Osmania | Mumbai Pattern — HIGH PROBABILITY
■ COLLECTIONS MAP COMPARISON

■ Answer:
Feature HashMap Hashtable LinkedHashMap TreeMap
Thread-safe? No Yes (slow) No No
Null keys? 1 null key allowed Not allowed 1 null key allowed Not allowed
Ordering No order No order Insertion order Sorted by key
Performance Fast O(1) Slower (sync) Slightly slower O(log n) tree
Introduced in Java 1.2 Java 1.0 (legacy) Java 1.4 Java 1.2
When to use General purpose Legacy code only Maintain insert order Sorted keys needed
HashMap<String,Integer> hm = new HashMap<>();
[Link]("Banana",3); [Link]("Apple",1); [Link]("Mango",2);
[Link](hm); // {Apple=1, Banana=3, Mango=2} — no order
TreeMap<String,Integer> tm = new TreeMap<>(hm);
[Link](tm); // {Apple=1, Banana=3, Mango=2} — alphabetical order
LinkedHashMap<String,Integer> lhm = new LinkedHashMap<>(hm);
[Link](lhm); // {Banana=3, Apple=1, Mango=2} — insertion order

Q80. What is instanceof operator? Explain with example. What is type casting in Java?
■ IGNOU | MDU Pattern — MEDIUM-HIGH PROBABILITY
■ COMMONLY ASKED SHORT QUESTION

■ Answer:
instanceof: binary operator that tests if an object is an instance of a particular class/interface. Returns true/false. Used before downcasting to prevent
ClassCastException.
Animal a = new Dog("Rex");
[Link](a instanceof Animal); // true — Dog IS-A Animal
[Link](a instanceof Dog); // true — actual type is Dog
[Link](a instanceof Cat); // false — Dog is not a Cat
// Safe downcast with instanceof:
if (a instanceof Dog) {
Dog d = (Dog) a; // safe cast — we verified it IS a Dog
[Link](); // Dog-specific method
}
// Without check — dangerous:
Cat c = (Cat) a; // ClassCastException at runtime!
Casting type Direction Example Risk
Upcasting Child → Parent Animal a = new Dog() Safe — automatic
Downcasting Parent → Child Dog d = (Dog) a Needs instanceof check
■ NOTE: Java 16 Pattern Matching instanceof: if(a instanceof Dog d){ [Link](); } — declares and casts in one line.

Java Complete Notes — GJU · IGNOU · MDU · Osmania · Mumbai | Page 28

You might also like