Docsity

Java Handwritten Notes: OOP, Inheritance, Polymorphism, Exceptions, Collections & Threads, Study notes of Java Programming

Partial preview of the text

Download Java Handwritten Notes: OOP, Inheritance, Polymorphism, Exceptions, Collections & Threads and more Study notes Java Programming in PDF only on Docsity!

Java Notes Date : 18]05]2025 1. Object Oyiented Programming (OOP) OOP is a programming paradigm based on the concept of “objects”, which can contain data and code +o manipulate that data. Key Features of OOPs : Encapsulation @ Class and Object e) Encapsulation Class & © Abstraction Object mee Abstraction @ Inheritance Principles ® Polymorphism Polymorphism Inheritance 11 Class and Object * Class is a blueprint or template for creating objects. © Object is an instance of a class. e A class can have attributes (variables) and methods (functions). Example : class Student { Here, int id; Student is a class. String name; st is an object of Student class. void display () { We can create multiple objects System. out.println Cid + of the same class. ™” + name); } Difference between Class and Object Class Object public class Test { public static vold main (String [] args) { Tt is a blueprint. | It is an instance Student si = new Student (); of a class. tdie= 104): are es No memory is Memory is allocated : = 3 ae F i : allocated. when object is ; $1. display () 5 |] Output: 101 Aman Ae } Declared usin Created using new class keyword . keyword. Note : Everything in Java is either a primitive (like int, char, ete.) or an object (like String, Scanner , Array List ete.). ee ee 2. Inheritance ‘ @® | Inheritance is a mechanism in OOPs in which one class acquires the properties (fields) and behaviors (methods) of another class. It promotes code reusability and establishes IS-A relationship. Key Points + © The class whose members are inherited is called Superclass (Parent class). @ The class that inherits is called Subclass (Child class) . ¢ In Java, inheritance is implemented using the extends keyword . ¢ A class can extend only one class (Single inheritance) . Superclass Feeeal (@ parent class) ee (base class) | extends D (child class) @ (derived class) Example : floss ‘Animal { public class Test { void eat() f{ public static void main(Stringl] args) { System. out. println (“Animal eats”) ; Dog due neu Dog () } d.eot(); // inherited method class Doq extends Animal { d.bark(); // own method void bark() { } ; System. out.. println (“Dog barks”) ; a 3 Output : Animal eats Dog barks Types of Inheritance in Java : Type Description Diagram Supported in Java? 1. Single One subclass inherits from ‘i ee one superclass. B Oe Mattclevel A subclass inherits from a AB be Yes subclass. 3. Hierarchical | Multiple subclasses inherit A from one superclass. ae a Yes 4. Multiple A subclass inherits from A 8 N lbs multiple superclasses . ee a tees) 5. Hybrid Combination of two or more A e types. a private members of superclass are not inherited. > Constructors ore not inherited. Java. supports multiple inheritance using Interfaces. > The subclass can access public and protected members of superclass. 4, Interfaces © An interface is a blueprint of a class. It contains abstract methods (methods without body) and constant fields. © A class implements an interface using the implements Keyword and provides the body of the methods declared in the interface. © Interfaces support multiple inheritance . Example : interface Shope { void area() ; } class Circle implements Shape { double r; Circle (double r) { thiset =) 3s i Syntax : public void area() { : System. out . println( “Area = - interface InterfaceNome { (3.14 #r #r)); return Type methodName ( parameters) ; If abstract ih I fields ore public static final by default } } class Test { : public static void main( Stringl ] orgs) { class ClassName implements InterfaceName { Girls c= yeu) Cirdle(5): Mf body of methods c-area(); // Output : Area = 78.5 } 5 } Note : Interface vs Abstract Class All methods in interface are public and Feature. Interface Abstract Class abstract by default. Methods Only abstract Abstract + > All voriobles in interface are public, methods (before Java 8)| concrete methods static and final by default . Variables public static final Can have any only type of variables Tnheritance | A class can A class can extend implement multiple only one abstract interfaces class Keyword implements extends 5. Exception Handling * Exception is an event that disrupts the normal flow of a program. * Jove handles exceptions using try, catch, finally, throw and throws keywords. © It improves the reliability of a program by handling errors gracefully . Syntax : try “t code that may throw exception : catch (ExceptionType e) { J] code to handle exception 3 finally { I] code thot will always execute } Example : Exception Hierarchy Object Throwable. Error Exception (Sertous problems (Conditions thot that programs a program can shouldn't try catch and handle) to catch) ieee tl Checked Unchecked. (Checked. at (Not checked at compile-time) Corrie stimne)) Types of Exceptions Type Example Checked Exceptions | TOException, SQLException, ClassNotFoundException Unchecked Exceptions | ArithmeticException, NullPointerException ArrayTndexOutOfBoundsException Errors OutOfMemoryError, StackOverflowError public class DivideExample { public static void main(String] args) { int a = 10, b = 0, result; try { result = a / b; System. out. println( “Result = "4 result); } catch (ArithmeticException e) { System. out. println( “Cannot divide by zero.”); } finally { System. out. println( “This is finally block.”); } } } Note : Flow of Exception Handling Code that may throw exception Rest. of the code... Exception occurred? Catch block. (Hondlait) J Finally block (always executes) Rest of the code... > “try? must be followed by at least one ‘catch’ or “finally”. > “finally” block is used to close resources (files, connections etc.). > Use specific exception classes for better exception handling . | 7. Multithreading ® © Multithreading allows a program to 4.4 Thread Life Cycle execute multiple threads (parts) concurrently to achieve maximum utilization of CPU. Q= Runnable (‘niy) Be (rita) © It improves performance and. responsiveness (Ready) of applications . i H 1 © Jove. provides built-in sup| rt for ae V vetifyO/ H | resume maliadin . wt eA fe ot) ale \ | Time-ouk 7 re i 1 | join / 41 Ways to Create a Thread a {yo / vA 4. Extending Thread. clase Go 2. Implementing Runnable interface New : Thread is created but not started. 4.2. Extending Thread class Runneble Really to ru ond! watting for CPUC © Create a class that extends Thread. Running > Currently executing . * Override run() method . Blocked/Waiting: Waiting for some event (I/O, sleep, lock etc.). © Call start() method to start execution . Terminated : Execution finished . | class MuyThread extends Thread { pulsed alt) 7.5 Important, Methods of Thread class for (int i= 4; i <= 5; itt) = System out println (Thread: * +5 |_ yey Method Description. ; ; calls run() | Start Starts the thread ond calls run() method. public class Demol { internally run() Contains the code to be executed by the thread. public static void main(StringL] args) { ino new J sleep(long ms) | Pauses the current thread for given milliseconds. MyThread £ = nea MyThread(); thread. ‘etn Woe Raesticaltineadl cae tistark(); Il starts the thread aa) fer to die. } yield) Causes the currently executing thread to } pause and allow other threads to execute. irewetieey i ae isAlive() Returns true if thread is olive. HS ree iaabes deine satPriovity (int p) | Sets priority (1 te 10). # Creake a class that implements Runnable . et Prior Ratan pricey ef thet Coed br Oserrsde Pea iretnad « i 40) lp) i : © Pass object to Thread constructor. 46 5 Bde ‘ iynchroniz. ne "Ene void oe a © Used to control access of multiple threads to for (int i= 4; <= 5; L++) shared resources . : System. out. printla ("Runnable : ” + i); © Achieved using synchronized keyword. } Mg dloss Counter { piblie clase Demo? oes Ree int count = 0; Only one. thread ee fe eer ar public. synchronized. oid. increment). { at a time con Tid Ue foul Tweed); _ count ++; execute this t.start(); } synchronized } } method . } Note > start) should be called only once on a thread. > Use Runnable interface (preferred) for better flexibility. > Always handle shared data using synchronization to ovoid data inconsistency . 4.4 Inter-Thread Communication using wait(), methods of Object class. Threads can communicate with each other notify() and notifyAll() 4.8 Daemon Thread * A thread that runs in background to perform supporting tasks. * JVM exits when all user (non-daemon) threads © A thread can be in waiting state until finish, even. if daemon threads are still running . another thread notifies it. © Use setDaemon(true) before starting the thread. e Must be used inside synchronized block . Bearole « Thread A Thread B class DoemonExample { ae ae public static void main(Stringl] args) { synchronized (obj) wait() synchronized (cbj) Thread t = new Thread(() -> { if releases lock “| { while(true) { obj -wait(); II some work System. out. printla( "Daemon Thread. Running”); # notify ()/ ae ie try { Thread..sleep(1000); } catch (Exception «) {} ae bj notifu(); d o / waiting nolL obj .no fy()s } 3 } Ds i t.setDaemon(true); // must be before stort() t.start(); Nemtias System. out.printin("Main threed ends”); notification } 2 4.4 Comparison : User Thread vs Daemon Thread Feature User (Non-Doemon) Thread Daemon Thread Purpose Perfacme mau tose tor epplsting Performs background / supporting tasks JVM Exit JVM waits for these threads to finish JVM does not wait for these threads Default New threads ore user threads by default Must be set explicitly using setDoemon (true) Use Cases UL, main processing , critical tasks Gorbage collection, background monitoring Priority Neel eee Low priority (generelly) F410 Important Thread Methods Method. Description Example start() Starts the execution of the thread . t.start(); run() Contains the code that is executed by the thread. Override run() in Thread class. sleep(ms) Pauses the current thread for given milliseconds. Thread . sleep (1000) ; yield() Gives a chance to other threads of same priority. | Thread. yield(); join() Waits for this thread to complete. t join) 5 isAlive() Checks if the thread is still running . t.isAlive() 5 setPriority(int p) | Sets priority (1 to 10). £. setPriority (Thread .MAX. PRIORITY); Note : > Prefer implementing Runnable over extending Thread (for better flexibllity) . » Always handle shored resources carefully to avoid race conditions . ° 8.5 Important Collection Interfaces Interface Description Collection | Root interface for all collection structures. List Ordered collection. (ollous duplicate elements) . Set Collection that does not allow duplicates. Queue Follows FIFO (First. In First Out) order. Map Stores data in key-value pairs. 8.8 Traversing Collections 8.6 Benefits of Collections Framework © Reduces Programming effort . © Improves performance and. code quality. * Tsleroperability bebeen different collection clasts. * Easy toi maintela ond update, © Provides: bulbcin methods fers commen’ peretione! 8.4 When to Use Which Collection? Use Requirement Maintain insertion order ArrayList or LinkedList * Collections provide iterator() method to traverse elements. * Con also use enhanced for loop. Example : Using iterator order ea dupliatan No dupliates, unordered | HoshSet No duplicates, sorted TreeSet import java Therator «String while (it hasNext@)) { System out println (it next()); abil; public class TraverseExample { public static void main(Stringl] args) { ArrayList list = new Arraglist<>(); list.add("A"); Uist.add("B"); listwadd("C”); > it = List. iterater(); Traverses ws Iterator } i y 8.9 Collection vs Traditional Arrays Feature Array Collection Size Fixed. Dynamic Type Can store ony sindar types | Con store objec (any tp) Methods | Limited Te ep Wall thats Ee eee fte rene Hore flee wed ey b ox 8.41 Summar % Collections Framework provides a standard architecture to store and manipulate groups of objects. H Tk consists of interfaces (Collection, List, Set, Queue, Map) and classes (ArrayList, HashSet, HashMap, ebc.). % Tk improves code reusability, readability ond reduces development time. # Always choose the right collection class based on the requirement for belter performance. FIFO order Tinhed list Cos Oueuely on Priority Queue Key-value. pairs HashMap 8.40 Sorting in Collections © Collections like List can be sorted using Collections.sort() method. © Custom sorting can be done using Comparator . Example : Sorting oa. List import java.util. *; public class SortExample { public static void main(Stringl] args) { ArrayList list = new Arraybist<>(); list.add (30); list.add (40); list.add (20); Collections. sort(list); ascending order System.out.println(list); // [40, 20, 30] i J