Java Complete 5university Notes
Java Complete 5university Notes
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:
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
■ 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.
■ Answer:
Type Size (bytes) Range Default
byte 1 −128 to +127 (256 values) 0
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"); }
}
■ 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; } }
■ Answer:
Multithreading: concurrent execution of multiple threads sharing heap memory within one process.
State Description
New Thread created — start() not called yet
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](); }
■ 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); }
}
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"); }
■ Answer:
■ 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)
■ 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);
■ 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]);
■ 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)
■ 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.
■ 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
}
■ 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)
■ Answer:
■ 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.
■ 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
■ 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
■ 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
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.
■ 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);
}
■ 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.
■ Answer:
■ 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)
■ 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)
■ Answer:
■ 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!
■ 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; }
}
■ Answer:
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.
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
}
■ 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
■ 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
■ 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){
■ 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!
■ 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.
■ 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]
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]());
■ 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
■ 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]();
■ Answer:
■ 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.
■ 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]();
}
■ 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
■ 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]());
■ 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
■ 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
■ 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);
■ 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]();
■ 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");
}
}
■ 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
■ 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]
■ 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)
■ 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
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
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.
GJU Singleton private ctor + private static instance + synchronized getInstance() → ONE object.
GJU Diamond Prob Multiple class inheritance banned. Interfaces solve via [Link]().
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.
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 Wrapper int→Integer, double→Double. Autoboxing: int→Integer auto. Unboxing: Integer→int auto.
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].
END OF COMPLETE NOTES — GJU · IGNOU · MDU · OSMANIA · MUMBAI | Best of luck! ■
■ 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.
■ 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) {
■ 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.
■ 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.
■ 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
■ 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");
■ 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!");
}
});
■ 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.
■ 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.
■ 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
■ 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) {
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.
■ 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"
■ 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.