📚 Chapters

☕ Project Based Learning in Java

Unit 2 — Advanced Java Programming & Database Connectivity

📚Chapter 2.1 — Collection Framework and Multithreading
📚 CHAPTER 2.1 — COLLECTIONS AND MULTITHREADING MIND MAP
Collections → List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap)
Choose → Index access: ArrayList. Frequent insert/delete at ends: LinkedList. No duplicates: Set. Key-value: Map
Threads → Create with Thread or Runnable. start() runs run() in a new thread
Life cycle → NEW → RUNNABLE → BLOCKED / WAITING / TIMED_WAITING → TERMINATED
Control → synchronized stops race conditions. Priority 1 to 10 is only a hint

1. Introduction to the Collections Framework

📖 Collection: an object that holds a group of other objects. The Collections Framework (package java.util) gives ready-made interfaces and classes to store, search, sort and remove objects.
💡 Analogy: An array is a fixed row of lockers. A collection is a flexible cupboard that grows and shrinks, with built-in shelves for sorting and searching.
ArrayCollection
SizeFixedGrows and shrinks automatically
StoresPrimitives and objectsObjects only (wrapper classes for primitives)
Ready methodsNo (only length)add, remove, contains, sort, size …
Type safetyYesYes, with generics: List<String>
CollectionMapListSetQueueArrayListLinkedListHashSetTreeSetPriorityQueueArrayDequeHashMapTreeMapCollection and Map are the two roots of the framework
InterfaceMain ideaDuplicates?Order
ListOrdered list with indexAllowedInsertion order
SetNo repeated elementsNot allowedDepends on class
QueueElements waiting in line (FIFO)AllowedQueue order
MapKey → value pairs (not a Collection)Keys unique, values can repeatDepends on class
Generics: List<String> means the list holds only Strings, so the compiler catches wrong types early. The utility class Collections offers sort(), reverse(), max() and more.

2. List: ArrayList and LinkedList

📖 ArrayList: a resizable array. Elements sit side by side, so reading by index is very fast.
📖 LinkedList: a doubly linked list. Every element is a node that points to the next and previous node, so adding or removing at the ends needs no shifting. It also works as a Queue and Deque.
ArrayList: one block of memory, elements side by side10[0]20[1]30[2]40[3]50[4]LinkedList: separate nodes joined by linksAmitNehaRajZoyablue = next link, orange = previous link
import java.util.*; public class ListDemo { public static void main(String[] args) { List<String> arr = new ArrayList<>(); arr.add("Amit"); arr.add("Neha"); arr.add("Raj"); arr.add(1, "Pooja"); // insert in the middle: later elements shift right System.out.println("ArrayList : " + arr + ", get(2) = " + arr.get(2)); LinkedList<String> link = new LinkedList<>(arr); link.addFirst("Zoya"); // at the beginning: no shifting needed link.removeLast(); // at the end: no shifting needed link.add(2, "Karan"); // middle: must walk to position 2 first System.out.println("LinkedList: " + link + ", first = " + link.getFirst()); Queue<Integer> queue = new LinkedList<>(); // LinkedList also works as a Queue / Deque queue.offer(10); queue.offer(20); queue.offer(30); System.out.println("poll() = " + queue.poll() + ", queue now = " + queue); } }
// Output ArrayList : [Amit, Pooja, Neha, Raj], get(2) = Neha LinkedList: [Zoya, Amit, Karan, Pooja, Neha], first = Zoya poll() = 10, queue now = [20, 30]
OperationArrayListLinkedList
get(i) by indexO(1) fastO(n) must walk the nodes
Add or remove at the beginningO(n) all elements shiftO(1)
Add or remove at the endO(1) on averageO(1)
Add or remove in the middleO(n) shiftingO(1) once the node is reached (finding it is O(n))
MemoryLessMore (two extra links per element)
When is LinkedList more efficient than ArrayList?
1) Frequent insertions and deletions at the beginning or middle (no shifting).
2) Using it as a queue, deque or stack (addFirst, removeFirst, offer, poll).
3) When you do not need random access by index.
4) When the size is unpredictable and elements are added or removed all the time.
Prefer ArrayList when you read by index often or mostly add at the end.

3. Set: HashSet, LinkedHashSet and TreeSet

📖 Set: a collection with no duplicate elements. Adding an element that already exists simply returns false.
import java.util.*; public class SetDemo { public static void main(String[] args) { Set<String> hs = new HashSet<>(); System.out.println(hs.add("Java") + " " + hs.add("Python") + " " + hs.add("Java")); // duplicate -> false System.out.println("HashSet size = " + hs.size() + ", contains Python = " + hs.contains("Python")); List<String> data = List.of("Mango", "Apple", "Banana", "Apple"); System.out.println("TreeSet (sorted) : " + new TreeSet<>(data)); System.out.println("LinkedHashSet (in order): " + new LinkedHashSet<>(data)); } }
// Output true true false HashSet size = 2, contains Python = true TreeSet (sorted) : [Apple, Banana, Mango] LinkedHashSet (in order): [Mango, Apple, Banana]
HashSetLinkedHashSetTreeSet
OrderNo guaranteed orderInsertion orderSorted (natural or Comparator)
SpeedO(1) on averageO(1) on averageO(log n)
Null allowedOne nullOne nullNo null
Works byHash tableHash table + linked listRed-black tree
Duplicates are detected using hashCode() and equals(). Use HashSet for fast membership tests and TreeSet when you need sorted data.

4. Map: HashMap and TreeMap

📖 Map: stores key → value pairs. Keys are unique. HashMap is fast and unordered. TreeMap keeps keys sorted. LinkedHashMap keeps insertion order.
import java.util.*; public class MapDemo { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>(); marks.put("Amit", 80); marks.put("Neha", 92); marks.put("Raj", 75); marks.put("Amit", 85); // same key: old value is replaced System.out.println("Amit = " + marks.get("Amit") + ", size = " + marks.size()); System.out.println("containsKey(Neha) = " + marks.containsKey("Neha")); Map<String, Integer> sorted = new TreeMap<>(marks); // TreeMap keeps keys sorted for (Map.Entry<String, Integer> e : sorted.entrySet()) System.out.println(e.getKey() + " -> " + e.getValue()); Map<String, Integer> wc = new TreeMap<>(); // word count for (String w : "to be or not to be".split(" ")) wc.put(w, wc.getOrDefault(w, 0) + 1); System.out.println(wc); } }
// Output Amit = 85, size = 3 containsKey(Neha) = true Amit -> 85 Neha -> 92 Raj -> 75 {be=2, not=1, or=1, to=2}
How HashMap works inside
  1. It calls key.hashCode() and turns it into a bucket number (default 16 buckets)
  2. If the bucket is empty, the entry is stored there
  3. If another key is already in the bucket (a collision), equals() checks for the same key. A same key replaces the old value, otherwise the entry is added to the bucket
  4. When the map is 75% full (load factor 0.75) it doubles the buckets and re-distributes the entries
HashMapTreeMap
Order of keysNot guaranteedSorted
Null keyOne allowedNot allowed
SpeedO(1) on averageO(log n)
Thread-safeNoNo
Which collection should I use?
NeedUse
Fast access by indexArrayList
Many inserts and deletes at the ends, queueLinkedList / ArrayDeque
No duplicates, fast lookupHashSet
No duplicates, sortedTreeSet
Look up a value by a keyHashMap
Key-value pairs sorted by keyTreeMap

5. Multithreading in Java

📖 Thread: a lightweight path of execution inside a program. Multithreading means running several threads at the same time in one program so the CPU is used better and the program stays responsive.
💡 Analogy: A restaurant kitchen with several cooks (threads) preparing different dishes at once, instead of one cook doing everything in turn.
ProcessThread
MeaningA running programA part of a process
MemoryOwn separate memoryShares the memory of its process
Creation costHeavyLight
CommunicationHardEasy (shared objects)
Creating threads
WayHowRemark
extends ThreadOverride run(), then call start()Cannot extend another class
implements RunnablePut code in run(), pass it to new Thread(r)Preferred. Class can still extend another class
class Worker extends Thread { // way 1: extend Thread Worker(String name) { super(name); } public void run() { for (int i = 1; i <= 3; i++) System.out.println(getName() + " step " + i); } } public class ThreadBasics { public static void main(String[] args) throws InterruptedException { Worker w = new Worker("Thread-A"); Thread r = new Thread( // way 2: pass a Runnable () -> System.out.println("Runnable task running in " + Thread.currentThread().getName()), "Thread-B"); w.start(); w.join(); // join(): wait, so the order is fixed r.start(); r.join(); System.out.println("main ends: " + Thread.currentThread().getName()); } }
// Output Thread-A step 1 Thread-A step 2 Thread-A step 3 Runnable task running in Thread-B main ends: main
start() vs run(): start() creates a new thread that then calls run(). Calling run() directly is an ordinary method call and runs in the current thread. Without join(), the order of output of two threads can change from run to run.

6. Thread Life Cycle

📖 Thread life cycle: the different states a thread passes through from creation to death. Java defines 6 states in Thread.State.
NEWRUNNABLETERMINATEDstart()endsBLOCKEDWAITINGTIMED_WAITINGwaiting for a lockwait() / join()sleep(ms) / wait(ms)solid = enters the state, dashed = returns to RUNNABLE
StateMeaningHow a thread gets there
NEWCreated, not startednew Thread(...)
RUNNABLEReady to run or running on the CPUstart()
BLOCKEDWaiting to get a monitor lockAnother thread holds the synchronized lock
WAITINGWaiting without a time limitwait(), join()
TIMED_WAITINGWaiting for a fixed timesleep(ms), wait(ms), join(ms)
TERMINATEDFinishedrun() ended or an exception was not caught
public class ThreadStates { public static void main(String[] args) throws Exception { Object lock = new Object(); Thread sleeper = new Thread(() -> { try { Thread.sleep(500); } catch (InterruptedException e) { } }); System.out.println("1) before start() : " + sleeper.getState()); sleeper.start(); Thread.sleep(100); System.out.println("2) inside sleep(500) : " + sleeper.getState()); sleeper.join(); System.out.println("3) after run() finished : " + sleeper.getState()); Thread blocked = new Thread(() -> { synchronized (lock) { } }); synchronized (lock) { // main holds the lock blocked.start(); Thread.sleep(200); System.out.println("4) main holds the lock : " + blocked.getState()); } blocked.join(); Thread waiter = new Thread(() -> { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { } } }); waiter.start(); Thread.sleep(200); System.out.println("5) inside wait() : " + waiter.getState()); synchronized (lock) { lock.notify(); } waiter.join(); System.out.println("6) after notify and end : " + waiter.getState()); } }
// Output 1) before start() : NEW 2) inside sleep(500) : TIMED_WAITING 3) after run() finished : TERMINATED 4) main holds the lock : BLOCKED 5) inside wait() : WAITING 6) after notify and end : TERMINATED
Important Thread class methods
MethodWhat it does
start()Starts the thread; the JVM then calls run()
run()Holds the code the thread executes
sleep(ms)Pauses the current thread for ms milliseconds (TIMED_WAITING)
join()Makes the caller wait until this thread finishes
yield()Hint that the current thread can let others run
interrupt()Asks a sleeping or waiting thread to stop waiting (InterruptedException)
isAlive()true if started and not yet finished
getState()Returns the current Thread.State
setPriority(n) / getPriority()Sets or reads the priority (1 to 10)
setName() / getName()Names a thread and reads its name
setDaemon(true)Makes a background thread (call before start())
Thread.currentThread()Returns the thread that is running this code
wait(), notify() and notifyAll() belong to the Object class, not Thread. They are used with synchronized blocks.

7. Thread Synchronization

📖 Race condition: two threads change the same data at the same time and the result becomes wrong. Synchronization lets only one thread at a time use a shared resource, using the lock (monitor) of an object.
💡 Analogy: One bathroom key. Whoever holds the key goes in, the others wait outside until the key is returned.
Why count++ is unsafe: it is three steps (read, add, write). Two threads can read the same value, so one update is lost. With 2 threads × 1000 increments the answer may be less than 2000.
class Counter { private int count = 0; synchronized void increment() { count++; } // only one thread at a time int get() { return count; } } public class SyncDemo { public static void main(String[] args) throws InterruptedException { Counter c = new Counter(); Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); }; Thread t1 = new Thread(task), t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final count = " + c.get()); } }
// Output Final count = 2000
FormExampleLock on
Synchronized methodsynchronized void increment()The object (this)
Synchronized blocksynchronized (lock) { … }The given object
Static synchronized methodstatic synchronized void m()The class
Deadlock: two threads each hold one lock and wait for the other, so neither can move. Avoid it by taking locks in the same order everywhere. Inter-thread communication: wait() releases the lock and waits, notify() wakes one waiting thread.

8. Thread Priority

📖 Thread priority: a number from 1 to 10 that tells the thread scheduler how important a thread is. A higher priority thread gets a better chance of the CPU, but there is no guarantee.
ConstantValue
Thread.MIN_PRIORITY1
Thread.NORM_PRIORITY5 (default)
Thread.MAX_PRIORITY10
public class PriorityDemo { public static void main(String[] args) { Thread low = new Thread(() -> { }, "Low"); Thread normal = new Thread(() -> { }, "Normal"); Thread high = new Thread(() -> { }, "High"); low.setPriority(Thread.MIN_PRIORITY); // 1 high.setPriority(Thread.MAX_PRIORITY); // 10 System.out.println("main priority = " + Thread.currentThread().getPriority()); for (Thread t : new Thread[] { low, normal, high }) System.out.println(t.getName() + " priority = " + t.getPriority()); try { low.setPriority(11); } // only 1 to 10 allowed catch (IllegalArgumentException e) { System.out.println("setPriority(11) -> IllegalArgumentException"); } } }
// Output main priority = 5 Low priority = 1 Normal priority = 5 High priority = 10 setPriority(11) -> IllegalArgumentException
  • A new thread inherits the priority of the thread that created it (main has 5)
  • setPriority() accepts only 1 to 10, otherwise IllegalArgumentException
  • Priority is only a hint. The result depends on the operating system, so never use it for correctness. Use synchronization for that
🧩Chapter 2.2 — Wrapper Classes, I/O Streams and Lambda Expression
🧩 CHAPTER 2.2 — WRAPPER CLASSES, I/O STREAMS AND LAMBDA MIND MAP
Wrapper classes → Integer, Long, Character, Boolean. Autoboxing and unboxing
I/O streams → Byte (InputStream/OutputStream), Character (Reader/Writer)
Serialization → Object ↔ bytes. transient fields are skipped
Lambda → (parameters) -> expression, functional interfaces, method references
Streams → filter, map, reduce, sorted, collect

1. Wrapper Classes

📖 Wrapper class: a class that wraps a primitive value in an object. Java has one for each primitive type.
PrimitiveWrapperPrimitiveWrapper
byteBytefloatFloat
shortShortdoubleDouble
intIntegercharCharacter
longLongbooleanBoolean
Why needed? 1) Collections store objects only, so List<int> is not allowed but List<Integer> is. 2) They give useful methods and constants (parse, compare, MAX_VALUE). 3) They can be null.
ClassCommon methods and constants
IntegerparseInt(), valueOf(), toString(), compare(), toBinaryString(), MAX_VALUE, MIN_VALUE
LongparseLong(), valueOf(), MAX_VALUE
CharacterisLetter(), isDigit(), isUpperCase(), toUpperCase(), getNumericValue()
BooleanparseBoolean() (true only for "true", ignoring case), valueOf()
public class WrapperDemo { public static void main(String[] args) { int n = Integer.parseInt("123"); // String -> int Integer boxed = Integer.valueOf(45); // int -> Integer object System.out.println((n + 1) + " " + boxed.doubleValue() + " " + Integer.MAX_VALUE + " " + Integer.compare(5, 9) + " " + Integer.toBinaryString(10)); long big = Long.parseLong("9876543210"); System.out.println(big * 2 + " " + Long.MAX_VALUE); char ch = 'a'; System.out.println(Character.isLetter(ch) + " " + Character.isDigit('7') + " " + Character.toUpperCase(ch) + " " + Character.getNumericValue('8')); System.out.println(Boolean.parseBoolean("TRUE") + " " + Boolean.parseBoolean("yes")); } }
// Output 124 45.0 2147483647 -1 1010 19753086420 9223372036854775807 true true A 8 true false

2. Autoboxing and Unboxing

📖 Boxing (autoboxing): the compiler automatically converts a primitive into its wrapper object (int → Integer).
📖 Unboxing: the compiler automatically converts a wrapper object back into a primitive (Integer → int).
int 10→autoboxing→Integer object→unboxing→int 10
AutoboxingUnboxing
DirectionPrimitive → ObjectObject → Primitive
ExampleInteger a = 10;int b = a;
In collectionslist.add(5)int x = list.get(0)
Before Java 5Integer.valueOf(10)a.intValue()
import java.util.*; public class BoxingDemo { public static void main(String[] args) { Integer a = 10; // autoboxing: int -> Integer (done by the compiler) int b = a; // unboxing: Integer -> int List<Integer> list = new ArrayList<>(); list.add(5); // autoboxing, because a list stores objects int first = list.get(0); // unboxing System.out.println(a + b + first); Integer x = 127, y = 127, p = 128, q = 128; System.out.println("127 == 127 : " + (x == y)); // cached objects (-128 to 127) System.out.println("128 == 128 : " + (p == q)); // different objects System.out.println("128 equals : " + p.equals(q)); Integer none = null; try { int z = none; } // unboxing null catch (NullPointerException e) { System.out.println("Unboxing null -> NullPointerException"); } } }
// Output 25 127 == 127 : true 128 == 128 : false 128 equals : true Unboxing null -> NullPointerException
Pitfalls: 1) Unboxing a null wrapper throws NullPointerException. 2) == on Integer compares references. Values from -128 to 127 are cached, so 127 == 127 is true but 128 == 128 is false. Use equals(). 3) Boxing inside big loops creates many objects and is slow.

3. I/O Streams: Byte Stream and Character Stream

📖 Stream: a flow of data between a program and a source or destination (file, keyboard, network). Byte streams handle raw bytes (any file). Character streams handle text and take care of character encoding.
Byte streamCharacter stream
Base classesInputStream, OutputStreamReader, Writer
Unit of data8-bit byte16-bit character
File classesFileInputStream, FileOutputStreamFileReader, FileWriter
BufferedBufferedInputStream, BufferedOutputStreamBufferedReader, BufferedWriter
Best forImages, audio, any binary fileText files
import java.io.*; public class FileIODemo { public static void main(String[] args) throws IOException { // Character stream: text try (FileWriter fw = new FileWriter("notes.txt")) { fw.write("Hello Java\nStreams are easy"); } try (BufferedReader br = new BufferedReader(new FileReader("notes.txt"))) { String line; while ((line = br.readLine()) != null) System.out.println("Read: " + line); } // Byte stream: copy any file, byte by byte int count = 0; try (FileInputStream in = new FileInputStream("notes.txt"); FileOutputStream out = new FileOutputStream("copy.txt")) { int b; while ((b = in.read()) != -1) { out.write(b); count++; } } System.out.println("Copied " + count + " bytes, copy.txt length = " + new File("copy.txt").length()); } }
// Output Read: Hello Java Read: Streams are easy Copied 27 bytes, copy.txt length = 27
try-with-resources closes the streams automatically, even if an error occurs. Standard streams: System.in (input), System.out (output), System.err (errors).

4. Object Serialization and Deserialization

📖 Serialization: converting an object into a stream of bytes so it can be saved in a file or sent over a network. Deserialization rebuilds the object from those bytes.
Object in memory→ObjectOutputStream→Bytes in a file→ObjectInputStream→New object
Rules for serialization
  1. The class must implement the marker interface java.io.Serializable (it has no methods)
  2. Write with ObjectOutputStream.writeObject(obj), read with ObjectInputStream.readObject() and cast
  3. Fields marked transient and static fields are not saved
  4. Add serialVersionUID so old files still match the class version
import java.io.*; class User implements Serializable { private static final long serialVersionUID = 1L; String name; int age; transient String password; // transient: this field is NOT saved User(String name, int age, String password) { this.name = name; this.age = age; this.password = password; } } public class SerializeDemo { public static void main(String[] args) throws Exception { User s = new User("Amit", 25, "secret123"); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"))) { out.writeObject(s); // serialization: object -> bytes in a file } System.out.println("Before : " + s.name + ", " + s.age + ", " + s.password); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"))) { User t = (User) in.readObject(); // deserialization: bytes -> new object System.out.println("After : " + t.name + ", " + t.age + ", " + t.password); } } }
// Output Before : Amit, 25, secret123 After : Amit, 25, null
Significance of transient: a transient variable is skipped. After deserialization it gets the default value (null, 0, false). Use it for (1) sensitive data such as passwords, (2) fields that are not serializable (Thread, Connection), (3) values that can be recomputed, (4) smaller saved data.
Drawback: the data is lost, so the program must re-initialise it after reading, or the object may behave wrongly.

5. Object Cloning

📖 Cloning: creating an exact copy of an object. The class must implement Cloneable and call super.clone() (Object.clone()). Otherwise CloneNotSupportedException is thrown.
Shallow copyDeep copy
Primitive fieldsCopiedCopied
Object fieldsOnly the reference is copied, so both objects share itThe referenced object is copied too
Change in originalVisible in the copyDoes not affect the copy
class Address implements Cloneable { String city; Address(String city) { this.city = city; } protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Person implements Cloneable { String name; Address address; Person(String name, Address address) { this.name = name; this.address = address; } Person shallowCopy() throws CloneNotSupportedException { return (Person) super.clone(); // address object is SHARED } Person deepCopy() throws CloneNotSupportedException { Person p = (Person) super.clone(); p.address = (Address) address.clone(); // address is copied too return p; } } public class CloneDemo { public static void main(String[] args) throws Exception { Person a = new Person("Amit", new Address("Delhi")); Person shallow = a.shallowCopy(); Person deep = a.deepCopy(); a.address.city = "Mumbai"; // change the original System.out.println("shallow copy city = " + shallow.address.city); System.out.println("deep copy city = " + deep.address.city); } }
// Output shallow copy city = Mumbai deep copy city = Delhi

6. Lambda Expressions and Functional Interfaces

📖 Lambda expression: a short, nameless method written as (parameters) -> expression. A functional interface is an interface with exactly one abstract method (can be marked @FunctionalInterface). A lambda gives the body for that method.
📐 Lambda syntax
No parameter: () -> System.out.println("Hi")
One parameter: n -> n * 2
Two parameters: (a, b) -> a + b
Block body: (a, b) -> { int s = a + b; return s; }
InterfaceMethodMeaning
Runnablerun()No input, no result
Predicate<T>test(t)Returns boolean
Function<T,R>apply(t)Input to output
Consumer<T>accept(t)Uses input, no result
Supplier<T>get()No input, gives result
BiFunction<T,U,R>apply(t,u)Two inputs, one output
Comparator<T>compare(a,b)Used for sorting
import java.util.*; import java.util.function.*; public class LambdaDemo { public static void main(String[] args) { Runnable r = () -> System.out.println("Hello from lambda"); r.run(); BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; // two parameters Predicate<Integer> isEven = n -> n % 2 == 0; // returns boolean Function<String, Integer> length = s -> s.length(); // input -> output Consumer<String> show = s -> System.out.println("Consumer got: " + s); // no result Supplier<Double> pi = () -> 3.14; // no input System.out.println(add.apply(3, 4) + " " + isEven.test(10) + " " + length.apply("lambda") + " " + pi.get()); show.accept("hello"); List<String> names = new ArrayList<>(List.of("Raj", "Amit", "Neha")); names.sort((a, b) -> a.compareTo(b)); // lambda as Comparator System.out.println(names); names.sort(Comparator.comparing(String::length)); // method reference System.out.println(names); names.forEach(System.out::println); // instance method reference Function<String, String> upper = String::toUpperCase; // arbitrary object method System.out.println(upper.apply("java")); Supplier<List<String>> maker = ArrayList::new; // constructor reference System.out.println(maker.get().size()); } }
// Output Hello from lambda 7 true 6 3.14 Consumer got: hello [Amit, Neha, Raj] [Raj, Amit, Neha] Raj Amit Neha JAVA 0

7. Method References

📖 Method reference: a shorter form of a lambda that only calls an existing method, written Class::method.
KindSyntaxSame as the lambda
Static methodInteger::sum(a, b) -> Integer.sum(a, b)
Instance method of an objectSystem.out::printlnx -> System.out.println(x)
Instance method of any object of a classString::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()
Each kind is used in the LambdaDemo program above (String::length, System.out::println, String::toUpperCase, ArrayList::new).

8. Stream API: filter, map, reduce, sorting

📖 Stream: a pipeline that processes the elements of a collection. It has a source, any number of intermediate operations (lazy) and one terminal operation. A stream does not change the original collection.
Source (List)→filter()→map()→sorted()→reduce() / collect()
Intermediate operations (filter, map, sorted) build the pipeline. A terminal operation (reduce, collect, forEach) starts it.
OperationTakesDoesResult type
filter()PredicateKeeps the elements that pass the testStream (fewer or equal elements)
map()FunctionTransforms every elementStream (same count, new values)
reduce()BinaryOperatorCombines all elements into one valueSingle value
sorted()Comparator (optional)SortsStream
collect()CollectorGathers the result into a List, Set …Collection
forEach(), count(), distinct(), limit()Other common operations
1 2 3 4 5 6→filter: even→2 4 6→map: square→4 16 36→reduce: sum→56
import java.util.*; import java.util.stream.*; public class StreamDemo { public static void main(String[] args) { List<Integer> nums = List.of(1, 2, 3, 4, 5, 6); System.out.println("filter (even) : " + nums.stream().filter(n -> n % 2 == 0).collect(Collectors.toList())); System.out.println("map (square) : " + nums.stream().map(n -> n * n).collect(Collectors.toList())); System.out.println("reduce (sum) : " + nums.stream().reduce(0, (a, b) -> a + b)); int result = nums.stream() .filter(n -> n % 2 == 0) // keep 2, 4, 6 .map(n -> n * n) // 4, 16, 36 .reduce(0, Integer::sum); // 56 System.out.println("sum of squares of even numbers = " + result); List<String> names = Arrays.asList("Raj", "Amit", "Neha", "Karan"); System.out.println("sorted by length, then name: " + names.stream() .sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())) .collect(Collectors.toList())); System.out.println("names starting with A or N : " + names.stream() .filter(s -> s.startsWith("A") || s.startsWith("N")) .map(String::toUpperCase) .collect(Collectors.toList())); } }
// Output filter (even) : [2, 4, 6] map (square) : [1, 4, 9, 16, 25, 36] reduce (sum) : 21 sum of squares of even numbers = 56 sorted by length, then name: [Raj, Amit, Neha, Karan] names starting with A or N : [AMIT, NEHA]
Sorting: a plain list can be sorted with list.sort(comparator) or Collections.sort(list). In a stream use sorted() or sorted(Comparator.comparing(...).thenComparing(...)).
🗄️Chapter 2.3 — JDBC
🗄️ CHAPTER 2.3 — JDBC MIND MAP
JDBC → Java API to talk to a database
Drivers → Type 1 JDBC-ODBC, Type 2 Native, Type 3 Network, Type 4 Thin (pure Java)
Steps → Driver → Connection → Statement → execute → ResultSet → close
CRUD → Create, Read, Update, Delete with PreparedStatement
Extras → MVC, Sequence, DUAL table, Date types

1. Database Connectivity and JDBC Basics

📖 JDBC (Java Database Connectivity): a Java API (java.sql) that lets a program connect to a database, run SQL and read results. The driver translates JDBC calls into the language of the particular database.
Java application→JDBC API→DriverManager→JDBC driver→Database
The steps of a JDBC program
  1. Add the JDBC driver (a JAR file) to the project
  2. Open a connection: DriverManager.getConnection(url, user, password)
  3. Create a Statement or PreparedStatement
  4. Execute: executeQuery() for SELECT, executeUpdate() for INSERT, UPDATE, DELETE
  5. Read the ResultSet with next() and getters
  6. Close everything (use try-with-resources)
Interface or classRole
DriverManagerChooses the driver and creates connections
ConnectionAn open session with the database
StatementRuns a fixed SQL string
PreparedStatementPrecompiled SQL with ? placeholders
CallableStatementCalls stored procedures
ResultSetThe rows returned by a query. Cursor starts before the first row
SQLExceptionAny database error
Since JDBC 4, Class.forName("driver") is optional. The driver in the classpath is found automatically.

2. Types of JDBC Drivers and Configuring Them

TypeNameHow it worksRemark
Type 1JDBC-ODBC bridgePasses calls to an ODBC driverSlow, needs ODBC on the PC. Removed in Java 8
Type 2Native-APIUses the database vendor client library (native code)Faster, but needs native software on every machine
Type 3Network protocol (middleware)Talks to a middleware server which talks to the databaseFlexible, extra server needed
Type 4Thin driver (pure Java)Talks to the database directly over the networkMost used, portable, no extra install
Configuring a driver
Steps
  1. Download the driver JAR (or add the Maven or Gradle dependency)
  2. Add the JAR to the project classpath (in an IDE: Build Path or Libraries)
  3. Use the correct driver class and URL for your database
  4. Open the connection with the user name and password
DatabaseDriver classURL format
MySQLcom.mysql.cj.jdbc.Driverjdbc:mysql://localhost:3306/dbname
Oracle (thin)oracle.jdbc.OracleDriverjdbc:oracle:thin:@localhost:1521:xe
PostgreSQLorg.postgresql.Driverjdbc:postgresql://localhost:5432/dbname
SQLiteorg.sqlite.JDBCjdbc:sqlite:file.db

3. Connection Example and CRUD Operations

📖 CRUD: Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE). The program below does all four on a student table.
import java.sql.*; public class JdbcCrud { static void showAll(Connection con) throws SQLException { try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT id, name, marks FROM student ORDER BY id")) { while (rs.next()) System.out.println(rs.getInt("id") + " | " + rs.getString("name") + " | " + rs.getInt("marks")); } } public static void main(String[] args) { // MySQL would be: jdbc:mysql://localhost:3306/college (plus user and password) String url = "jdbc:sqlite::memory:"; try (Connection con = DriverManager.getConnection(url)) { try (Statement st = con.createStatement()) { // CREATE st.executeUpdate("CREATE TABLE student (id INT PRIMARY KEY, name VARCHAR(50), marks INT)"); } String insert = "INSERT INTO student (id, name, marks) VALUES (?, ?, ?)"; try (PreparedStatement ps = con.prepareStatement(insert)) { // INSERT Object[][] rows = { {1, "Amit", 80}, {2, "Neha", 92}, {3, "Raj", 75} }; for (Object[] r : rows) { ps.setInt(1, (int) r[0]); ps.setString(2, (String) r[1]); ps.setInt(3, (int) r[2]); ps.executeUpdate(); } } System.out.println("After INSERT:"); showAll(con); // READ try (PreparedStatement ps = con.prepareStatement("UPDATE student SET marks = ? WHERE id = ?")) { ps.setInt(1, 90); ps.setInt(2, 1); // UPDATE System.out.println("Updated rows: " + ps.executeUpdate()); } try (PreparedStatement ps = con.prepareStatement("DELETE FROM student WHERE id = ?")) { ps.setInt(1, 3); // DELETE System.out.println("Deleted rows: " + ps.executeUpdate()); } System.out.println("After UPDATE and DELETE:"); showAll(con); } catch (SQLException e) { System.out.println("Database error: " + e.getMessage()); } } }
// Output After INSERT: 1 | Amit | 80 2 | Neha | 92 3 | Raj | 75 Updated rows: 1 Deleted rows: 1 After UPDATE and DELETE: 1 | Amit | 90 2 | Neha | 92
The output above comes from running this exact code on an embedded SQLite database. For MySQL only the URL, user and password change (and the driver JAR). The JDBC calls stay the same.
StatementPreparedStatement
SQLFixed text, values joined into the stringPrecompiled SQL with ? placeholders
Speed for repeated useSlowerFaster
SQL injectionUnsafeSafe, values are never treated as SQL
Example"... WHERE name='" + n + "'""... WHERE name = ?" then setString(1, n)
SQL injection: if you join user input into SQL, input like x' OR '1'='1 can change the query. Always use PreparedStatement.

4. MVC Model for Project Development

📖 MVC (Model–View–Controller): a way to split a project into three layers so that data, display and logic stay separate.
UserControllerModelViewrequestupdate / readshowdataModel = data + DB code, View = display, Controller = logic
LayerJobIn our JDBC project
ModelData and database logicStudent class and StudentDAO (JDBC code)
ViewWhat the user seesStudentView (prints, or a JSP or Swing screen)
ControllerTakes the request, calls the model, picks the viewStudentController
import java.sql.*; import java.util.*; class Student { // MODEL: the data int id; String name; int marks; Student(int id, String name, int marks) { this.id = id; this.name = name; this.marks = marks; } } class StudentDAO { // MODEL: database access (JDBC) private final Connection con; StudentDAO(Connection con) throws SQLException { this.con = con; try (Statement st = con.createStatement()) { st.executeUpdate("CREATE TABLE student (id INT PRIMARY KEY, name VARCHAR(50), marks INT)"); } } void save(Student s) throws SQLException { try (PreparedStatement ps = con.prepareStatement("INSERT INTO student VALUES (?, ?, ?)")) { ps.setInt(1, s.id); ps.setString(2, s.name); ps.setInt(3, s.marks); ps.executeUpdate(); } } List<Student> findAll() throws SQLException { List<Student> list = new ArrayList<>(); try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM student ORDER BY id")) { while (rs.next()) list.add(new Student(rs.getInt(1), rs.getString(2), rs.getInt(3))); } return list; } } class StudentView { // VIEW: only displays void show(List<Student> list) { System.out.println("ID NAME MARKS"); for (Student s : list) System.out.println(s.id + " " + s.name + " " + s.marks); } } class StudentController { // CONTROLLER: connects the two private final StudentDAO dao; private final StudentView view; StudentController(StudentDAO dao, StudentView view) { this.dao = dao; this.view = view; } void addStudent(int id, String name, int marks) throws SQLException { dao.save(new Student(id, name, marks)); } void showStudents() throws SQLException { view.show(dao.findAll()); } } public class MvcDemo { public static void main(String[] args) throws Exception { try (Connection con = DriverManager.getConnection("jdbc:sqlite::memory:")) { StudentController c = new StudentController(new StudentDAO(con), new StudentView()); c.addStudent(1, "Amit", 80); c.addStudent(2, "Neha", 92); c.showStudents(); } } }
// Output ID NAME MARKS 1 Amit 80 2 Neha 92
Benefits: easy to change one layer without touching the others, easy testing, teamwork (one person per layer), and reusable code. A DAO (Data Access Object) keeps all SQL in one place.

5. Sequence and Dual Table

📖 Sequence: a database object that generates unique numbers one after another (1, 2, 3 …), mostly used for primary keys. Oracle has CREATE SEQUENCE with NEXTVAL and CURRVAL. MySQL uses an AUTO_INCREMENT column instead.
📖 DUAL table: a special table with one row and one column in Oracle (MySQL also accepts the name). It is used when you need to run a SELECT that does not read any real table.
-- SQL (Oracle / MySQL) CREATE SEQUENCE student_seq START WITH 1 INCREMENT BY 1; INSERT INTO student VALUES (student_seq.NEXTVAL, 'Amit', 80); SELECT student_seq.NEXTVAL FROM DUAL; -- next unique number SELECT SYSDATE FROM DUAL; -- current date and time of the server SELECT 10 * 5 FROM DUAL; -- evaluate an expression
try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT SYSDATE FROM DUAL")) { if (rs.next()) System.out.println("Server time: " + rs.getTimestamp(1)); }
These Oracle examples were not run here because they need an Oracle server. The output of the last query is the current time of the database server.
Role of DUAL in JDBC: 1) get the server date and time (SYSDATE), 2) fetch the next sequence value before an insert, 3) evaluate expressions or functions, 4) test the connection (SELECT 1 FROM DUAL is used as a validation query).

6. Date Type Management in Java

📖 Date types: Java and SQL have different date classes, so values must be converted when using JDBC.
ClassHoldsUse
java.util.DateDate and time (old)Avoid in new code
java.sql.DateDate only (yyyy-mm-dd)SQL DATE columns
java.sql.TimeTime onlySQL TIME columns
java.sql.TimestampDate + time + fractionSQL TIMESTAMP, DATETIME
java.time.LocalDate, LocalDateTimeModern date and time APIPreferred for new code
import java.time.*; import java.time.format.DateTimeFormatter; public class DateDemo { public static void main(String[] args) { LocalDate d = LocalDate.of(2026, 11, 22); java.sql.Date sqlDate = java.sql.Date.valueOf(d); // LocalDate -> java.sql.Date (for JDBC) LocalDate back = sqlDate.toLocalDate(); // java.sql.Date -> LocalDate System.out.println("sql.Date : " + sqlDate); System.out.println("formatted : " + d.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); System.out.println("plus 10 days : " + back.plusDays(10)); java.sql.Timestamp ts = java.sql.Timestamp.valueOf(LocalDateTime.of(2026, 11, 22, 10, 30, 0)); System.out.println("Timestamp : " + ts); System.out.println("Time : " + java.sql.Time.valueOf("10:30:00")); } }
// Output sql.Date : 2026-11-22 formatted : 22-11-2026 plus 10 days : 2026-12-02 Timestamp : 2026-11-22 10:30:00.0 Time : 10:30:00
// store a date ps.setDate(1, java.sql.Date.valueOf(LocalDate.of(2026, 11, 22))); // read a date LocalDate d = rs.getDate("joining").toLocalDate();
Format dates for display with DateTimeFormatter.ofPattern("dd-MM-yyyy"). Never store dates as plain Strings in the database.
⚡Ready for Exam?Sab padh liya? Ab Quick Revision karo — code, key points aur PYQ ek jagah!Quick Revision Karo →
⚡Quick Revision — Last Minute Exam Prep!
📌 How to use: Har topic mein pehle Definition, phir Example, phir Diagram hai.

📚 Chapter 2.1 — Collections and Multithreading

1. Collections Framework
📖 Definition: A framework of ready-made interfaces and classes to store and process groups of objects.
💡 Example: List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap).
CollectionMapListSetQueueArrayListLinkedListHashSetTreeSetPriorityQueueArrayDequeHashMapTreeMapCollection and Map are the two roots of the framework
2. ArrayList vs LinkedList
📖 Definition: ArrayList is a resizable array (fast index access). LinkedList is a doubly linked list (fast insert or delete at ends).
💡 Example: Queue with offer() and poll() on a LinkedList.
ArrayList: one block of memory, elements side by side10[0]20[1]30[2]40[3]50[4]LinkedList: separate nodes joined by linksAmitNehaRajZoyablue = next link, orange = previous link
ArrayListLinkedList
get(i)O(1)O(n)
Add at startO(n)O(1)
3. HashSet, TreeSet, HashMap
📖 Definition: Set has no duplicates. HashMap stores key to value pairs using hashCode() and buckets.
💡 Example: TreeSet of Mango, Apple, Banana, Apple gives [Apple, Banana, Mango].
Order
HashSet / HashMapNot guaranteed
LinkedHash…Insertion order
TreeSet / TreeMapSorted
4. Thread Life Cycle
📖 Definition: Six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.
💡 Example: sleep(500) shows TIMED_WAITING. wait() shows WAITING.
NEWRUNNABLETERMINATEDstart()endsBLOCKEDWAITINGTIMED_WAITINGwaiting for a lockwait() / join()sleep(ms) / wait(ms)solid = enters the state, dashed = returns to RUNNABLE
5. Synchronization and Priority
📖 Definition: synchronized lets one thread at a time use shared data. Priority 1 to 10 is only a hint.
💡 Example: Two threads x 1000 increments with synchronized gives exactly 2000.
PriorityValue
MIN1
NORM (default)5
MAX10

🧩 Chapter 2.2 — Wrappers, I/O, Lambda

1. Wrapper Classes and Boxing
📖 Definition: Wrapper classes wrap primitives in objects. Autoboxing: primitive to object. Unboxing: object to primitive.
💡 Example: Integer a = 10; int b = a; 127 == 127 is true but 128 == 128 is false.
int 10→autoboxing→Integer object→unboxing→int 10
2. Byte vs Character Streams
📖 Definition: Byte streams (InputStream, OutputStream) for any data. Character streams (Reader, Writer) for text.
💡 Example: FileWriter writes text, FileInputStream copies any file byte by byte.
ByteCharacter
ClassesInputStream / OutputStreamReader / Writer
3. Serialization
📖 Definition: Object to bytes (writeObject) and back (readObject). transient fields are not saved.
💡 Example: User with transient password: after deserialization password = null.
Object in memory→ObjectOutputStream→Bytes in a file→ObjectInputStream→New object
4. Lambda and Method References
📖 Definition: Lambda: (params) -> body for a functional interface. Method reference: Class::method.
💡 Example: (a, b) -> a + b and String::toUpperCase
InterfaceMethod
Predicatetest()
Functionapply()
Consumeraccept()
Supplierget()
5. Streams: map, filter, reduce
📖 Definition: filter keeps, map transforms, reduce combines into one value.
💡 Example: 1 to 6: even → 2 4 6, square → 4 16 36, sum → 56.
1 2 3 4 5 6→filter: even→2 4 6→map: square→4 16 36→reduce: sum→56

🗄️ Chapter 2.3 — JDBC

1. JDBC Steps
📖 Definition: Java API to connect to a database: connection, statement, execute, ResultSet, close.
💡 Example: executeQuery() for SELECT, executeUpdate() for INSERT, UPDATE, DELETE.
Java application→JDBC API→DriverManager→JDBC driver→Database
2. Driver Types
📖 Definition: Type 1 JDBC-ODBC, Type 2 Native, Type 3 Network, Type 4 Thin (pure Java, most used).
💡 Example: MySQL: com.mysql.cj.jdbc.Driver and jdbc:mysql://localhost:3306/db.
TypeName
1JDBC-ODBC bridge
2Native-API
3Network protocol
4Thin (pure Java)
3. CRUD, MVC
📖 Definition: CRUD = INSERT, SELECT, UPDATE, DELETE. MVC splits Model (data and DAO), View, Controller.
💡 Example: PreparedStatement with ? placeholders prevents SQL injection.
UserControllerModelViewrequestupdate / readshowdataModel = data + DB code, View = display, Controller = logic
4. Sequence, DUAL, Dates
📖 Definition: Sequence gives unique numbers. DUAL is a one-row Oracle table for SELECT without a real table. java.sql.Date for SQL dates.
💡 Example: SELECT SYSDATE FROM DUAL; Date.valueOf(LocalDate).
-- SQL (Oracle / MySQL) SELECT SYSDATE FROM DUAL; SELECT student_seq.NEXTVAL FROM DUAL;
📄Previous Year Questions
📌 In Semester Test-2, Academic Year 2026-2027 — Unit 2. Subject: Project Based Learning in Java (24CSH-301 / 24ITH-301), BE(CSE/IT), Semester 5. Maximum Marks: 20, Time: 1 Hour.
Section A (5 × 2 = 10 marks)
2M2026-27
Q1. Discuss in what scenarios is LinkedList more efficient than ArrayList. [CO3]▼
Answer:
LinkedList is a doubly linked list, so it is more efficient than ArrayList when the program works mostly at the beginning, end or middle and not by index.
ArrayList: one block of memory, elements side by side10[0]20[1]30[2]40[3]50[4]LinkedList: separate nodes joined by linksAmitNehaRajZoyablue = next link, orange = previous link
  • Frequent insertions and deletions at the beginning or middle: no shifting of elements
  • Queue, deque or stack operations: addFirst(), removeFirst(), offer(), poll()
  • No need for random access by index
  • Size changes often and unpredictably
OperationArrayListLinkedList
get(i)O(1)O(n)
Add or remove at the startO(n)O(1)
Add or remove at the endO(1)O(1)
MemoryLessMore
2M2026-27
Q2. Explain the concept of thread priority in Java with a suitable example. [CO3]▼
Answer:
Thread priority is a number from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default 5 (NORM_PRIORITY). The scheduler may give a higher priority thread more chances to run, but it is only a hint, not a guarantee.
public class PriorityDemo { public static void main(String[] args) { Thread low = new Thread(() -> { }, "Low"); Thread normal = new Thread(() -> { }, "Normal"); Thread high = new Thread(() -> { }, "High"); low.setPriority(Thread.MIN_PRIORITY); // 1 high.setPriority(Thread.MAX_PRIORITY); // 10 System.out.println("main priority = " + Thread.currentThread().getPriority()); for (Thread t : new Thread[] { low, normal, high }) System.out.println(t.getName() + " priority = " + t.getPriority()); try { low.setPriority(11); } // only 1 to 10 allowed catch (IllegalArgumentException e) { System.out.println("setPriority(11) -> IllegalArgumentException"); } } }
// Output main priority = 5 Low priority = 1 Normal priority = 5 High priority = 10 setPriority(11) -> IllegalArgumentException
A thread inherits the priority of its parent. setPriority() outside 1 to 10 throws IllegalArgumentException.
2M2026-27
Q3. Discuss the role of a dual table in JDBC. [CO4]▼
Answer:
DUAL is a special one-row, one-column table in Oracle (MySQL accepts it too). It lets you run a SELECT when no real table is needed.
  • Get the server date and time: SELECT SYSDATE FROM DUAL
  • Get the next sequence value: SELECT seq.NEXTVAL FROM DUAL
  • Evaluate an expression or function: SELECT 10 * 5 FROM DUAL
  • Test the connection: SELECT 1 FROM DUAL (validation query)
ResultSet rs = st.executeQuery("SELECT SYSDATE FROM DUAL"); if (rs.next()) System.out.println(rs.getTimestamp(1));
2M2026-27
Q4. Explain boxing and unboxing. [CO4]▼
Answer:
Boxing (autoboxing) = automatic conversion of a primitive to its wrapper object (int → Integer). Unboxing = automatic conversion of a wrapper object to a primitive (Integer → int). The compiler does both, for example when adding to a collection.
int 10→autoboxing→Integer object→unboxing→int 10
import java.util.*; public class BoxingDemo { public static void main(String[] args) { Integer a = 10; // autoboxing: int -> Integer (done by the compiler) int b = a; // unboxing: Integer -> int List<Integer> list = new ArrayList<>(); list.add(5); // autoboxing, because a list stores objects int first = list.get(0); // unboxing System.out.println(a + b + first); Integer x = 127, y = 127, p = 128, q = 128; System.out.println("127 == 127 : " + (x == y)); // cached objects (-128 to 127) System.out.println("128 == 128 : " + (p == q)); // different objects System.out.println("128 equals : " + p.equals(q)); Integer none = null; try { int z = none; } // unboxing null catch (NullPointerException e) { System.out.println("Unboxing null -> NullPointerException"); } } }
// Output 25 127 == 127 : true 128 == 128 : false 128 equals : true Unboxing null -> NullPointerException
Unboxing null throws NullPointerException. Compare wrappers with equals(), not ==.
2M2026-27
Q5. Explain the differences between map(), filter(), and reduce() in Java Streams with examples. [CO4]▼
Answer:
map()filter()reduce()
JobTransforms each elementSelects elements by a conditionCombines all elements into one value
TakesFunctionPredicate (true/false)BinaryOperator
Output sizeSame number of elementsEqual or fewerSingle value
Example (1 to 6)square → 1 4 9 16 25 36even → 2 4 6sum → 21
1 2 3 4 5 6→filter: even→2 4 6→map: square→4 16 36→reduce: sum→56
import java.util.*; import java.util.stream.*; public class StreamDemo { public static void main(String[] args) { List<Integer> nums = List.of(1, 2, 3, 4, 5, 6); System.out.println("filter (even) : " + nums.stream().filter(n -> n % 2 == 0).collect(Collectors.toList())); System.out.println("map (square) : " + nums.stream().map(n -> n * n).collect(Collectors.toList())); System.out.println("reduce (sum) : " + nums.stream().reduce(0, (a, b) -> a + b)); int result = nums.stream() .filter(n -> n % 2 == 0) // keep 2, 4, 6 .map(n -> n * n) // 4, 16, 36 .reduce(0, Integer::sum); // 56 System.out.println("sum of squares of even numbers = " + result); List<String> names = Arrays.asList("Raj", "Amit", "Neha", "Karan"); System.out.println("sorted by length, then name: " + names.stream() .sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())) .collect(Collectors.toList())); System.out.println("names starting with A or N : " + names.stream() .filter(s -> s.startsWith("A") || s.startsWith("N")) .map(String::toUpperCase) .collect(Collectors.toList())); } }
// Output filter (even) : [2, 4, 6] map (square) : [1, 4, 9, 16, 25, 36] reduce (sum) : 21 sum of squares of even numbers = 56 sorted by length, then name: [Raj, Amit, Neha, Karan] names starting with A or N : [AMIT, NEHA]
Section B (2 × 5 = 10 marks)
5M2026-27
Q6. Examine the different states in the Java thread life cycle and analyze how Thread class methods facilitate thread management and execution. [CO3]▼
Answer:
Thread life cycle: a thread moves through 6 states (Thread.State).
NEWRUNNABLETERMINATEDstart()endsBLOCKEDWAITINGTIMED_WAITINGwaiting for a lockwait() / join()sleep(ms) / wait(ms)solid = enters the state, dashed = returns to RUNNABLE
StateMeaningThread class method that leads to it
NEWCreatednew Thread()
RUNNABLEReady or runningstart()
BLOCKEDWaiting for a lockentering a synchronized block
WAITINGWaits without limitjoin(), wait()
TIMED_WAITINGWaits for fixed timesleep(ms), join(ms)
TERMINATEDFinishedrun() completes
public class ThreadStates { public static void main(String[] args) throws Exception { Object lock = new Object(); Thread sleeper = new Thread(() -> { try { Thread.sleep(500); } catch (InterruptedException e) { } }); System.out.println("1) before start() : " + sleeper.getState()); sleeper.start(); Thread.sleep(100); System.out.println("2) inside sleep(500) : " + sleeper.getState()); sleeper.join(); System.out.println("3) after run() finished : " + sleeper.getState()); Thread blocked = new Thread(() -> { synchronized (lock) { } }); synchronized (lock) { // main holds the lock blocked.start(); Thread.sleep(200); System.out.println("4) main holds the lock : " + blocked.getState()); } blocked.join(); Thread waiter = new Thread(() -> { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { } } }); waiter.start(); Thread.sleep(200); System.out.println("5) inside wait() : " + waiter.getState()); synchronized (lock) { lock.notify(); } waiter.join(); System.out.println("6) after notify and end : " + waiter.getState()); } }
// Output 1) before start() : NEW 2) inside sleep(500) : TIMED_WAITING 3) after run() finished : TERMINATED 4) main holds the lock : BLOCKED 5) inside wait() : WAITING 6) after notify and end : TERMINATED
How Thread class methods help manage threads: start() begins execution, sleep() pauses, join() makes one thread wait for another, yield() lets others run, interrupt() wakes a waiting thread, setPriority() hints importance, getState() and isAlive() report status, setDaemon() makes background threads.
5M2026-27
Q7. Analyze the concepts of serialization and deserialization in Java, and critically assess the significance of transient variables during the serialization process with the help of a suitable program. [CO4]▼
Answer:
Serialization converts an object into a byte stream (to save in a file or send over a network). Deserialization rebuilds the object from the bytes. The class must implement Serializable.
Object in memory→ObjectOutputStream→Bytes in a file→ObjectInputStream→New object
import java.io.*; class User implements Serializable { private static final long serialVersionUID = 1L; String name; int age; transient String password; // transient: this field is NOT saved User(String name, int age, String password) { this.name = name; this.age = age; this.password = password; } } public class SerializeDemo { public static void main(String[] args) throws Exception { User s = new User("Amit", 25, "secret123"); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"))) { out.writeObject(s); // serialization: object -> bytes in a file } System.out.println("Before : " + s.name + ", " + s.age + ", " + s.password); try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"))) { User t = (User) in.readObject(); // deserialization: bytes -> new object System.out.println("After : " + t.name + ", " + t.age + ", " + t.password); } } }
// Output Before : Amit, 25, secret123 After : Amit, 25, null
Significance of transient (critical assessment)
BenefitDrawback
Keeps sensitive data (password) out of the fileThe value is lost: it becomes null, 0 or false after reading
Skips fields that cannot be serialized (Thread, Connection)The program must re-initialise the field, or the object may misbehave
Skips values that can be recomputed and keeps files smallNeeds extra code (custom readObject) when the value matters
static fields are also not serialized, because they belong to the class, not the object.