Download as pdf
Download as pdf
You are on page 1of 42
OBJECT ORIENTED PROGRAMMING WITH JAVA HANDWRITTEN TOPIC « Exception handling e Input output basic f{ultithreading Object Oriented Programming with Java Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File Structure, and Compilation. Fundamental, Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access Specifies, Static Members, Final Members, Comments, Data types, Variables, Operators, Control Flow, Arrays & String, Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding, Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class, Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library Packages, Import and Static Import Naming Convention For Packages Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception, Control Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw, throws in ‘ception Handling, in-built and User Defined Exceptions, Checked and Un-Checked Exceptions. Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java. “sem )/Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread Priorities, Synchronizing ‘Threads, Inter-thread Communication. Java New Features: Functional Interfaces, Lambda Expression, Method References, Stream API, Default Methods, Static Method, Base64 Encode and Decode, ForEach Method, Try-with: resources, Type Annotations, Repeating Annotations, Java Module System, Diamond Syntax with Inner Anonymous Class, Local Variable Type Inference, Switch Expressions, Yield Keyword, Text Blocks, Records, Sealed Classes Java Collections Framework: Collection in Java, Collection Framework in Java, Hierarchy of Collection Framework, Iterator Interface, Collection Interface, List Interface, ArrayList, LinkedList, Engineering Express need to find a way to overcome it and_continue running. Similarly, y a le continue functioning. Exception can arises due to various reasons:- «File Not Found «Individual User Input « Programming Errors | Example: class MainClassé i —_. (String Tp) ie int RWerew t7/Sh 42 TINE Ee Pe EIN? eee | System. out.printlnC Hello’); | System.out.printin(af3}); | System.out.printh(a[3])); | System out.printInC' De TZ 3 2 Idea Behind Excepti CWhat_Is Exception Handling?) The Exception handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. Exception handling is responding to exceptions when a computer program runs. Engineering Express How to han ions? As we know, exceptions are like unexpected problems that disrupt the normal flow of your program: To handle exceptions we use try-catch block and_finally block. try: Wrap the risky code Cwhere an exception might occur). |catch: Specify what todo if an_exception happens. | finals ln_fi > ; or not. Example: public class ExceptionHandlingExample £ public staticvoid main(Stringl) args) fo nyt Fi ou int_result = 10 / 0; A ? Ari rT | Handle the exception System.out.printInC Oops! Something went wrong: "+ __| le.getMessage()); i finally £ System.out.printInC This is the finally block’); 2 Engineering Express In_this example: ) in whi . eee) & . , | The finally block executes after the try-catch block, regardless of _| F |clt’s useful for cleanup tasks Clike closing files or releasing resources). | Errors are problems that mainly occur due to the lack of system resources, It cannot be caught or handled. It indicates a serious problem, It occurs at_run_ time. These are always unchecked. There is | no chance for recovery. | Example: OutOfMemoryError, LinkageEnor, AssertionEnor, etc. ___| Basis of _ Exception Error Exceptions are issues within| Errors are serious system-level try to catch and handle. your program’s control. Exception can be recovered Recoverable/ by using the try-catch An error cannot be recovered. Irrecoverable block. It can be classified into two . All errors in Java are Type categories i.e. checked and unchecked, unchecked. It occurs at compile time or . Occurrence It occurs at run time. run time. It belongs to It belongs to Package io a Jjava.lang.Exception package. | java.lang.Error package. Definition your program that you can | issues that are usually beyond || __ Engineering Express Known or | Only checked exceptions are | Errors will not be known to unknown | known to the compiler. the compiler. It is mostly caused by the it is mainly coused by the mene Causes environment in which the application itself. oo . application is running. Types Of Exception There are mainly two_types of exceptions: Checked Exceptions: These are the exceptions that you need to take |care of while writing your code. The-compiler checks these at_compile- | . nF : Fe if you : Readéile £ public static void main(String] args) £ uy f // Trying to open_a_file that may not exist FileInputStream file = FilelnputStream('somefile.txt'); R j Ai 2 catch CFileNotFoundException e) £ This block handles the FileNotFoundException System out,printInC Oops! File not found,"); Engineering Express does not check. They occur during the execution of the program, and aa, lt Fart if you try to divide a number by zero, Java will throw an ArithmeticException. Here’s an example: public class DivideByZero £ public static void main(Stringl} args) £ int_a = S> int _b = 0; imp This will cause _an_ArithmeticException an int_result = a_/_b; RIN HT 3 catchCArithmeticException e) § " 1 " In this example, dividin ill th n_ArithmeticException . 9 . . program from crashing. Control Flow In Exception: In Java, contro) flow in exception handling dictates how the program proceeds when an exception occurs. Here’s a simplified explanation with an example: Engineering Express Control Flow Steps: ltry block. Ti |that matches the type of exception thrown, Finally Block: After the catch block executes, the finally block runs if || it_is present, The finally block executes regardless of whether an exception was caught_or not. Continuation: After the finally block Cor after the catch block if finally is not present), the program continues with the rest of the |code. [= A an | Example: i B - inde f 5 ae in(StringL] df Ne (SINUINE CRIN Ea Code that-_may throw an exception int result = 10 / 0; ae meni , loccurs'), LZ fi eT | Handling the exception System,out.printInC Caught an ArithmeticException' biomenccecention 3 finally £ This block will always execute System,out. printInC This _is the finally block’); 2 System.out.printinC Program continues here..."); Engineering Express © ln_this_ example: a I caught. The finally block executes next, printing its message. Finally, the program continues with the next statement after the ‘inally block, which is the last print statement, IThis control flow ensures that your program can handle exceptions gracefully and continue running or terminate cleanly. JVM Reaction To Exception ) : . ian. of ad || Java Virtual Machine C1VM) takes the following steps to_handle it: if , ram 1 ; |this as an ArithmeticException TA ion: The JVM ion obj A lerror. This object contains information about the error, including its | type and the state of the program when the error occurred. f ~The JVM ing fi ; handler that can handle the exception, It begins with the method where the exception occurred and moves up the call stack, checking each _methoa’s exception table for a matching catch block. Transfer Control: If a suitable handler is found, the JVM transfers contro) to the catch block. The program counter is set to the new location, and execution continues from there. Engineering Express |to the console. i | For Example: public class ExceptionExample £ public_static void main(Stringl] args) £ try £ int result = divideCl0,0); // This will throw an ArithmeticException $ catch CArithmeticException-e) € System .out.printlnC Exception caught:" + 22; $ finally € _____ System .out.printInC This will always be printed."); _ i i public static int divideCint_a, int b) £ LL. yeturn RUSEEEDIISIOVELMCERONEI IO i 2 E |In this code: An ArithmeticException_is thrown in the divide method, The JVM creates an ArithmeticException object. It searches for a handler, finds one in the main method, and transfers contro) to that catch block. The finally block is executed after the catch block. Engineering Express © and finally blocks: try Block: This block contains code that might throw an exception. It’s a way to test_a_block of code for errors while it’s being executed. try £ Code that may throw an exception Z Block: If . . || catches it. You can have multiple catch blocks to handle_different 1 ¢ ‘ons. WF if ifi =m |catch (ExceptionType name) § SSCs Code to handle the exception TA 2 finally Block: This block is optional and contains code that is alway: lexecuted, regardless of whether an exception was thrown or caught. | It’s typically used for cleanup activities like closing file streams or database connections. finally £ Code that will always execute 2 Example of a program already explained above. Engineering Express | The primary purposes of these blocks ave = er Ts cdafien f ; Th . fi fp |when an exception occurs. finally: To execute code after the try-and catch blocks, regardless of always runs, such as resource cleanup. This structure helps maintain_the normal flow of the application even when unexpected events (exceptions) occur, USE of Throw Keyword |For waderstanding purpose: : f er, teryn. Imagine you're playing a game where you have to follow certain rules. p iy. |you’ve detected something that shouldn't happen, It’s a way for your | program to say, “I can’t handle this situation, so I’m going to let someone else deal with it.” Here’s an easy example: public class BirthdayPorty £ public static void main(String[] args) £ inviteFriendC' Charlie"), inviteFriendC"); // Uh-oh, we forgot to write a name here! Engineering Express |be empty!"); i System,out.printinC Invitation sent to" + name); 2 In this_program, we have a method called inviteFriend that sends an |name.If we forget and send an empty name, the throw keyword | enna reach 4 So, the throw keyword is used to_create an error on_purpose when OR WS (For Examination Purpose) Ind , a‘ , exception handling by allowing you to explicitly throw _an_exception, It _| gives you the contro) to generate an exception from a method or any f in i 7 : followed by an instance of Throwable class or its subclasses, Here’s a simple explanation with an example: Example: Let’s say you have a method that calculates the division of two numbers, You want to make sure that the denominator is not invitation to a friend, But we need to make sure we write the friend's |\_ Engineering Express ic static void main(Stringl] aros) £ [ iy £ L Ln = Systemout,printinC The result is: "+ result); = | ? catch CArithmeticException e) £ System .out.printInCEnor:." + e,getMess : 2 _public_static int divideCint_ numerator, int denominator) £____||_ if Cdenominatar == 0) £ Foe) Sian a | £ Ht ___return_numerator / denominator, 3 L F L [In the above code: | If it_is, it throws an ArithmeticException with the message “Cannot || divide by zero”. Fel paeh a . e q prepared to handle the exception, If the exception is thrown, the catch block catches it and prints the error message. This is how the throw keyword is used to create a controlled response to an exceptional condition in your code. It’s particularly useful for Engineering Express © I indicate that this method might throw certain types of exceptions, It’s a way for the method to tell the compiler and the developers using the method that they need tobe aware of and handle these potential ||__ issues when they call the method. Here’s a detailed explanation with an example: | Example: Suppose you havea method_that reads a file and processes | : Readli fi \ file mi : ; ae it TI exceptions that_you expect could happen, and you want to warn Lanyone who-uses your method about them. import java.io.*;> . ee B This method declares that it might throw an |OException ___| public static String readFileCString fileName) throws lOException _| £ BufferedReader reader = new BufferedReader(new FileReader(fileName)); ty ft retum_reader.readLineQ; 3 finally £ reader.close(); Engineering Express © my £ We) |JOException String content =_readFil System. i 3 catch (lOException e) £ Here we handle the exception if it_occurs System.out.printInC Problem reading the file: " + e.getMessage()); 2 3 Lin the veadFile method: es We use throws lOException to declare that_this method might throw | lan lOException. ¢ b : like. if Ai eager) Ae lout of the readFile method. [In the main method: an_exception. en , printing an error message. So, the throws keyword doesn’t handle the exception itself: it just doesn’t handle the exception, the program will crash if that exception occurs. tells the caller of the method that they should handle it, If the caller_|\_ OR Engineering Express © jme. Here’s how it works with an example: Imagine you have a program that’s like a library. You have a method called readBook, which is like trying to take a book off the shelf and read it, But sometimes, the book might not be there, and that’s a | problem i , f Thi aoe LFileNeneaund exception tN TS EI PRIN? Bea a. Book(Styi ) Fi ES ion f File book = new FileCbookName); if Clbook.exists)) £ If the book isn't there, we have a problem, and we let lit be known, throw new FileNotFoundExceptionC'S\ " + bookName + " is not available."); 2 If the book is there, you can read it (code to read the book goes here). 2 2 Engineering Express Lis the warning label. _____|| Inside the method, if the book isw’t there, we use throw to actually | So, throws is all about giving a heads-up that there might be issues, and it’s up to the person using the method to be prepared for them. It’s like telling your friend_to bring an umbrella because it might rain—it’s better to be ready just in case Difference Between Throw And Throws | Differences throw throws Java throw keyword is used throw | Java throws keyword is used in the an exception explicitly in the code, | method signature to declare an exception Definition inside the function or the block of code, which might be thrown by the function ihile the execution of the code. Type of exception Using throw keynord, we can only propagate unchecked exception i., the checked exception cannot be propagated using throw only. Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only. The throw keyword is followed by The throws keyword is followed by class Syntox an instonce of Exception to be | names of Exceptions to be thrown. thrown. Decloration | EHOW IS used within the method. | throws is used with the method signature. We are allowed to throw only one | We can declare multiple exceptions using Internal exception at a time i.e. we cannot | throws keyword that can be thrown by ‘implementation | throw multiple exceptions. the method. For example, main() throws 10Exception, SQLException Engineering Express In-Built Excopti | For Understanding Purpose Java system uses to tell you something went wrong while your program was running, Think of them_as automatic alerts that pop up to_let you know there’s a problem that needs fixing, Here's an easy example: [imagine you have a box with S apples, and_you try to take out the | RB , NS — ist Cwhich 1 il ani put OfR Exception. It’s Java’ f saying, you're trying to get something that isn’t there!” ltry £ intl] appleBox = £1, 2, 3, 4, 53: // A box with 5 apples ———_| int nonExistenthpple = appleBoxIS]; // Oops! There's no 6th ___| apple. rraylndex ‘Bounds Exceptit 2 In this code, we're trying to get the 6th apple CappleBox[S] because in Java we start counting from 0), but since it’s not there, Java tells us with an exception, We catch that exception and print a message to understand what went wrong. That’s how inbuilt exceptions work in Java. Engineering Express 1 ht . ; fined i ibravie ) ic iti |that may occur during the execution of a program, Here are some of | the key built-in exceptions in Java with examples: ArithmeticException: This exception is thrown when an exceptional arithmetic condition has occurred, such as dividing by zero. try £ | _ipta = 30 b= “a SS ltry £ intL]_a = new ints]; al6] = 9; Accessing an index outside the array size |? catch CArraylndexOutOfBoundsException e) § = System.out.printInC Array Index is Out Of Bounds'); 2 ClassNotFoundException: This exception is raised when an application tries to load a class through its string name using methods like Engineering Express Mass fi 0 ike A ; ie FileNotFoundException: This_exception_is thrown when an attempt to open the file denoted by a specified pathname has failed. ty t FileReader fr = new FileReaderC nonexistenttile.txt'); |? catch CFileNotFoundException-e) a 2 These are just_a few examples of built-in exceptions in Java. There oa EL EP h Fi exelent thi Out OFB a . fi Pp . ime oN a : ; ; ; for buildi an Pull error conditions without crashing. User-Defined Exceptions === = User-defined exceptions in Java are custom exceptions that you create for handling specific error situations that the standard exceptions do not cover, They are particularly useful when you want your program to throw an exception that has a specific meaning within your Engineering Express > i HI if lalready have overdue books, You can create a ct i OverdueBookException for this specific scenario. First, you detine your custom exception class by extending the Exception class: class OverdueBookException extends Exception f public OverdueBookException(String message) £ SIRT Geet | —_—_. ~~ Va 3 2 publiaNdigss Hiv EN OD TING ES ERE INS Eee public void-borrowBook(String bookld, Member member) throws _ | | OverdueBookException fd if Cmember.hasOverdueBooks()) £ throw new OverdueBookExceptionC Member has overdue | books and cannot borrow more."): 2 —— Logic to borrow the book 2 In_ the borrowBook method, you check if the member has any overdue books, If they do, you throw an OverdueBookException, which you can |\_ then catch and handle appropriately: public class Main £ public static void main(Stringl] args) £ Engi ineering Express Library library = new Library ); Member member = new Me is ty f Jil 2 System.out.printIn(e,getMessageQ); 2 In the main method, when you call borrowBook, you handle the OverdueBookException in a_catch block, This way, you can provide a _____|| meaningful message to the user_and_prevent them from borrowing | 5 - dei ; specific to the needs of your application. Aspect Inbuilt Exceptions User-Defined Exceptions Pre-made error types thot Jova provides to | Custom error types thot you ereote for specific What are they? oe ° tile ™ handle common issues. conditions in your program. Where do they | Part of the Jove language in Created by programmers using come from? | the javalang package the Exception closs o its f | There are two main types of multitasking in Java: Process-Based Multitasking (Multiprocessing): This involves running multiple processes at the same time. Each process is an independent program with its own memory space. ‘rocesses are isolated from each other and communicate through inter-process communication (IPC) t’s more secure because an error in one process doesn’t affect the thers, but it’s also heavier on system resources Engineering Express Thread-Based Multitasking (Multithreading): THREAD thread is like a lightweight sub process within a program. Vt allows multiple tasks to run at the same time and it improves the lresources and faster program execution = = Efficient. R Si a memory and resources, multithreading can be more resource-efficient | compared to multiprocessing. Responciienece: Aaah input and other tasks at the same time. Time-Saving: Performing multiple operations at the same time can save time. Independence of Threads: If an exception occurs in one thread, it doesn’t necessarily affect the execution of other threads. Engineering Express : a nS ; a ie vies 2h on Lifecycle of thread |New (Born) States When a thread is created, it’s in the New state It has not yet started to execute. Runnable (Ready-to-Run)_State: A_thread in this state is ready to_run and just waiting for CPU time. It’s either running or ready to run_as soon as it gets the CPU, |Running State: | When the thread scheduler-selects the thread from the Runnable pool, | Al ut q ? O ape Blocked/Waiting State f , tO [Waiting State: A ~ 5 ee perform a particular action without any time limit. It happens when waitQ, joinC) without timeout, or Ais Timed Waiting State: A_thread is in this state when it waits for another thread to perform a_specific action for a specified period. It occurs when Thread sleep, waitO, join) with timeout, or LockSupport.parkNanos()/parkUntilC_is called. Terminated (Dead) State: Engineering Express © How to create thread in java Creating threads in Java_can be done using two main methods: by extending the Thread class or by implementing the Runnable interface. |\_ |Here’s how you can do it with both methods: | Extending the Thread Class: | Define a Class that Extends Threads || Create a new class that extends the Thread class, — = ____ 1 verti 0 fi : Lexecute, | Instantiate the Class; | Create an instance of the class you've defined. ____ Start the Thread: | Call the startO_method on the instance to begin its execution _| vlemanting: thes Runnable Tberface- Define a Class that Implements Runnable: Create a new class that implements the Runnable interface. | | Engineering Express © ‘ 1 2 x P | constructor. Start the Thread: Thread Priority threads are scheduled for execution. It’s like giving threads a priority number at a busy restaurant—the higher the number, the sooner the thread gets to ‘eat’ CPU_time, Here’s a detailed look at thread priority: Thread priority in Java is a feature that determines the order in which || Priority Levels: 5 ls 10. |The JVM _uses these priority levels as hints to decide which thread to Lrun first Default. Priovitij: | Setting Priority: | You can change a thread’s priority using the setPriorityCint ____——_| newPriority) method. = ae ar ital Cmaximum). Constants: Java defines three constants for convenience: MIN_ PRIORITY: The lowest priority, witha value of | NORM_PRIORITY: The default priority, with a value of S. MAX_PRIORITY: The highest priority, with a value of 101. Engineering Express © | Scheduler’s Role: on their prioritie. v Loperating system. i 5 ? In a multi-threaded environment, setting thread priorities can help ensure that more important tasks are completed first, But be cautious—overusing priorities can lead to “starvation,” where lower priority threads never get a_chance to_run| Here’s an example of setting and getting thread priorities in Java: lava. |class MyThread extends Thread § | wilavoig pe otNE Pins Be CR "+ getName()): ” F ‘vite , SnelninGninaliLaro8 MyThread tl = new MyThreadO; tl.setNameC Thread-!"); TI MI 1 priority MyThread t2 = new MyThreadO; t2.setName('Thread-2"); t2.setPriority(Thread.MAX_PRIORITY), // Set to maximum priority Engineering Express © tLstartQ; t2.startQ); 3 3 in te oo — = a maximum, When the threads are started, the JVM will consider these priorities when scheduling the threads for execution Inter- Ci inicatic LInter-thread communication in Java_is a mechanism that allows y 4 , concepts: |methods used for inter-thread communication in Java. tO: C nan F |notifyO or notifyAllO on the same object. = notify): Wakes up a single waiting thread on the same object. yall ba waiti . Usage: These methods must be called from within a synchronized block or method to work correctly. Example: Engineering Express © [alas Message f while Cempty) £ waitO, 2 empty = true; notifyAllO; return_msQ; i : . We ye while Clempty) £ wait(); \\ | NVUIN RIN ne D vitaxafalee* mso = Wiessage: notifyAllO; 3 E |In this example, takeOwaits for putO_to send a message, and putO_| waits for take) to receive the message before sending a new Lonel2 34 java.util.concurrent Package: Besides waitO, notifyO), and notifyAllO. Java provides higher-level constructs like BlockingQueue, CountDownLatch, Semaphore, etc., for inter-thread communication Engineering Express 7 F an | Purpose: Synchronization is used to prevent thread interference and | memory consistency errors when multiple threads access shared resources. synchronized Keyword: Java provides the synchronized keyword to create synchronized methods or blocks. Synchronized Methods: When a method is declared as synchronized, it_||_ [lacks the object for any other_thread that-tries to_access the | synchronized method. s ped B . f Jocki F ; f ae Locks: Every object has_an_intrinsic lock associated _with it. When a ane ; A: . Static 5 ication: If , " ; : - ; BE Andividual | instance. | Inter-Thread Communication: Synchronization also involves waitO, notifyO), and notifyAll methods that allow threads to communicate labout the lock status |class Counter £ private int_count = 0; public synchronized void increment() £ count++; Engineering Express © multiple threads try to increment count, they will do.so without interfering with each other, Advantages: ¢ Ensures that only one thread can execute a block of code ata time. on f . ; Wat |____from multiple threads, | Disadvantages: Can _lead_to thread_contention, where multiple threads try to __| 7 : .» j ele

You might also like