Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

OOPS With Java Unit 2

Notes java oops

Uploaded by

deezguys369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
15 views

OOPS With Java Unit 2

Notes java oops

Uploaded by

deezguys369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 42
Object Oriented Programming with Java AKTU Unit :- 2 BCS-403 Exception Handling 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 Exception Handling, In-built and User Defined Exceptions, Checked and Un-Checked Exceptions. An exception is something that is left out or not done on purpose. An exception to a rule does not follow that rule. In Java “an event that occurs during the execution of a program that disrupts the normal flow of instructions” is called an exception. This is generally an unexpected or unwanted event which can occur either at compile-time or run-time in application code. The Idea Behind Exceptions ‘An exception usually signals an error and isso called because errors in your Java programs are bound to be the exception rather than the rule—by definition! An exception doesn't always indicate an error thought can also signal some particularly unusual event in your program that deserves special attention If you try to deat with the myriad and often highly unusual error conditions that might arse in the midst of the code that deals With the normal operation of the program, your program structure will soon become very complicated and difficult to understand, ‘One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of en: forcing a response to particular errors. With many kinds of exceptions, you must include cade in your program to deal with them; otherwise, your code will not compile « cxenton YG ever ) Errors V/s Exceptions v In Short errors and exceptions represent different types of problems that can occur during program execution. Errors are usually caused by serious problems that cannot be recovered from, while exceptions are used to handle recoverable errors within a program. Types of Exception Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Exceptions can be categorized into two ways 1. Built-in Exceptions © Checked Exception © Unchecked Exception 2. User-Defined Exceptions Major reasons why an exception Occurs Invalid user input Device failure Loss of network connection Physical limitations (out-of-disk memory) Code errors * Opening an unavailable file Exception Hierarchy All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error is used by the Java run-time systemUVM) to indicate errors having to do with the run-time environment itself URE). StackOverflowError is an example of such an error, publi state void main(String args) in datas500,//may trow exception ‘jtemoutprinin est ofthe code Control Flow in Exceptions publi clas TCatchExampe ava, Lane Arithmeticeiception: / by 26F8 JVM Reaction to Exceptions The JVM starts the search from the method where the exception occurred and then goes up the call stack, checking each method in turn for a catch block that can handle the exception. If a catch block is found, the JVM transfers control to that block and the exception is considered to be handled. Exception Handling In Exception handling , we should have an alternate source through which we can handle the Exception. Advantage of Exception Handling ‘The core advantage of exception handling is to maintain the normal flow of the application, An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider statement Suppose there are 10 statements ina Java program and an exception occurs at statement §; the rest of the statement 2 code will not be executed ie, statements 6 to 10 will not be executed. However, when we perform exception statement 3 handling, the rest ofthe statements will be executed. Thats why we use exception handing in Java. one statement S//exception occurs Java Exception Keywords = | aces statement 9 lic class TyCatchbcampe Java uses keyword “try” to preface a block of code that is likely to ee eee ‘cause an error condition and “throw” an exception. whe state vld main tng os ‘The try block can have one or more statements that could generate cE al ty an exception. : try = int data=50/0; /may throw exception { d statement ; // generates an exception ‘handing the exception } 2 > sfend of ery eaten (tyexceptton «) ¢ Runtime Error printstacktrace(); MEKCEPon Balance is 1ess\than 000 > a8 ytaception ain fleoreperty. ja Detalts of account numbers, customer names, and balance amounts are taken inthe form of thee arays In. maing) method, the details are displayed using a forloop. At this time, a check s done iin any account the balance amount is less than the minimum balance amount tobe apt in the account titi so, then MyException is raised and » message is displayed “Balance Input / Output Basics Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java. File 10 In Java, we can read data from files and also write data in files. We do this using streams. Java has many input and output streams that are used to read and write data. Same as a continuous flow of water is called water stream, in the same way input and output flow of data is called stream. Stream Java provides many input and output stream classes which are used to read and write. Streams are of two types. A atts Sa * Byte Stream * Character Stream ‘These streams can be different in how they are handling data and the type of data they are handling Byte Streams: Byte streams are designed to deal with raw binary data, which includes al kinds of data, including characters, pictues, audio, and video. These streams are represented through cclasses that cease with the word “InputStream’ or "OutputStream" of their namesalong with FilelnputStream BufferedinputStream, FileOutputStream and ButferedOutputStream. Byte streams offer a low-stage interface for studying and writing character bytes or blocks of bytes. They are normally used for coping with non-textual statistics, studying and writing files of their binary form, and running with network sockets. Byte streams don't perform any individual encoding or deciphering, They treat the data as a sequence of bytes and don't interpret it as characters. Character Streams: Character streams are designed to address character based records, which includes textual records inclusive Of letters, digits, symbols, and other characters. These streams are represented by way of training that quit with the phrase "Reader" or “Writer” of their names, inclusive of FileReader, BufferedReader, FileWriter, and BufferedWriter. CCharacter streams offer a convenient manner to read and write textual content-primarily based information due to the fact they mechanically manage character encoding and decoding. They convert the individual statistics to and from the underlying byte circulation the usage of a particular individual encoding, such as UTF-eight or ASCILIt makes person streams suitable for operating with textual content files, analyzing and writing strings, and processing human-readable statistics. Classes — ‘Byte Stream Character ‘lasses co Taput stream os Byte Stream Classes: ioe 8 bts car ‘OutputStream — py chews InputStream : OutputStream Fig Cascaion ova Stream Classes BurferedinputStream -BurferedOutputStream Byterayinpustream ByteArrayOutputStream Datanpusteam DataOutputStream ‘Objectnput Stream" -ObjectOutputStream. FleinputStream FleOutputStream PipedinputStream PipedOutputStream ou InputStream Qutputstream FilterinputStream nputsieam —_ E-BaterOutputstream. outputs RggtStroam tt) pte “roa an wrt bah ry methods fy team Example code for Byte Stream: Import jaaio ByteArayinputvear Public clas BjteSteaméxample ‘i publi state void maining) args) ( 1) Creates teary fs byte) ray = (19203040 wt BjedraynputSteam inpt-new Byteieraynputtveamiany) ‘Sjtemout prin The bytes read am the np rea forint =0caraylengthie) 1 1 Reads te bytes Int datasinputread Sjtem out priate) ) inputcose cate Exception eo) canst oxo ) ‘he bytes read from the input strean:ie,22, 30,48 ) Example code for Character Stream: Import jnaiaCharrayReader, Import jaialOEscepton: ‘public les CharecterSveamExanpe 1 publi state vod mating aa ( 1) Coates an ary of characters char aay = (46/0 wy! ‘CharrayReader eadersmew CharkrayReadearay ‘ystemoutpint( The characters ead from the reader" int chorea while (charead=readerread)!=-1){ Sytem out print charicharead 1 reader ose catch (OEscepione) ‘exprinstackracey , output ’ ‘ihe characters read from the readerstye,1u1.0, Reading from a file: Step 1: Step 2: Step 3: Step 4: Step 5: Reading and Writing File in Java 1. In Java, the FilelnputSream class is used for reading binary data from a file. 2. Itis an input stream that reads bytes from a file in a file system. 3.To read data from a file using FilelInputStream, these steps you need to follow :- Create an instance of the FilelnputStream class and pass the path of the file that you want to read as an argument to its constructor. Create a byte array of a fixed size to read a chunk of data from the file. Use the read() method of the FilelnputStream class to read data from the file into the byte array. This method returns the number of bytes read , or -1 if the end of the file has been reached. Continue reading data from the file until the read() method returns -1. Close the FileInputStream object using to release the close() method to release any system resources associated with it. Following example demonstrates how to use Fileinputstream to read data from a file : import java.io.* ublic class ReadFileExample { Inthe emplelevove WoC oa Oe eee PI FilelnputStream object to read data public static void main(String[] args) { fee teadiel eke try{ . Enélnputstreamm fleinput. U/ sin river method public static void main(String{] args) 4 11 Creating randon threads 11 with the help of above class ‘Treaddeno ti » new Threaddeno(); ‘TrrendDeno £2 = new Threaddeno(); ‘Treaddeno £3 + new Threaddeno(); 11 Thread 2 1/ splay the priority of above theese 1/ using getPriority() method systen.out.printin("ti thread priority eaigeterforsey())s system.out.printin(“t2 thread priority © 4 s2ugetrgorsty())s U1 Tareas 3 System.out.printin("*3 thread priority + ea.getPrtorsty(0)5 11 Setting priorities of above threads by 11 passing integer argonent ta.seterdority(2)s talaetPriority(3)s ta.setPriority(@); “ uw ts.setpriority(21); will throw Tilegalargunentexception wa systen.out.printin("ti thread priority + ehagetrréority())5 us system.out.printin(“t2 thread priority © + e2igetPrdorsty())s ue systen-out.printin("t3 thread priority + s.getPrdority0) 1) Wa theese 1/ Displays the nane of 1) corrently executing Thread = systen.cut.prinein¢ “currently fxecuting Thread : " + Theend.currentTareag)gettne())5 + systen-out.printin¢ “hain theese préorsty + Threae.currentTaread() getoriority()); 11 Rain thread pricrity is set to 10 ‘Thread. currentThrend()-setPetalty(10); ‘ysten.out-printin¢ hain threes priarsty ¢ * + theeae.currentTaread().getoriority()); > ? ~ Output tH thread priority : 5 42 thread priority + 43 thread priority ‘1 thread priority 42 thread priority + 43 thread priority : 8 ‘currently Executing Thread ¢ Main thread priority : 5 Main thread priority : 10 Synchronization in Ji Synchronization in java is the capability to control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource. Why use Synchronization ‘The synchronization is mainly used to 1, To prevent thread interference. 2. To prevent consistency problem. Types of Synchronization ‘There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization JAVA CONCURRENCY Synchronized Thread Synchronization There are two types of thread synchronization mutual exclusive and inter- thread communication. 1. Mutual Exclusive 1. Synchronized method. 2. Synchronized block. 3. static synchronization. 2. Cooperation (Inter-thread communication in java) Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1. by synchronized method 2. by synchronized block 3. by static synchronization Concept of Lock in Java Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. From Java 5 the package java.util.concurrent.locks contains several lock implementations. 1. //example of java synchronized method 2. class Table{ 3. synchronized void printTable(int n){//synchronized method 4. for(int ie1si<=53i+4)t yor Thre 5. System.out.printin(n*i); a 6. tryt % es 7. Thread,sleep(400); 7. ee 8. _jeatch(Exception e}(System.out. printin(e) ee Bo ) 29. public void run(}{ . , 30. tprintTable(100); -? a} eS } oa) 14. class MyThread1 extends Thread me ye 1 fees nee ot 35. public static void main(String args|)){ = @ 36. Table obj = new Table();//only one object me 37. MyThreadi t1=new MyThread1 (obj); 19. public void run(} ee 20. tprintTable(5); 40. t2'start)): 2} = ee 22. a2} 23. ) Inter-thread communication in Java Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is @ mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executedit is implemented by following methods of Object class: + wait() =e + notify() Drees) + notifyAll() | al Tees) — (Ga 1) wait() method The wait() method causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. public final void wait()throws interruptedException Itwaits until object is notified. public final void waitflong timeout)throws InterruptedException It waits for the specified amount of time. 2) notify() method The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: lic final void notify) 3) notifyAll() method Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll() Why wait(), notify() and notifyAll() methods are defined in Object class not Thread Class? It is because they are related to lock and object has a lock. Difference between wait and sleep? “The wait) method releases the lock. ‘The sleep() method doesn't release the lock. Iti a method of Object class Iie a method of Thread caee Itis the non-static method leis the static method It should be notified by notify) or notifyAll) After the specified amount of time, sleep is methods completed Understanding the process of inter-thread communication Entry Set The Owner Wait Set Jwatin tobe net vies -@ @ The point to point explanation of the above diagram is as follows: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wat() method on the object. Otherwise it releases the lock and exits 4. If you call notfy() or notifyAll method, thread moves to the notified state (runnable state) 5. Now thread is available to acquire lock 6. After completion of the task, thread releases the lock and exits the monitor state of the object. Example of Inter Thread Communication in Java class Customer int armount=10000; -gmnchronized void withdraw(nt amourt{ ‘Systemoutprntn( going to withdraw.) if(thisamountcamount} ‘Systemoutprntin( Less balance; waiting for deposit." ‘ry(wait(Jeateh(Exceptione)) ) this amount-=amount: ‘Systemoutprintin( withdraw completed.” ) synchronized void deposit{int amount) ‘System outprintin("going to deposit.) this amount + =amount; ‘System outprintin(‘deposit completed... notify0; ) ) class Test( public static void main(String args) final Customer c=new Customer) ee public void run()(c.withdraw(15000);) — }start0; a wisn ese aman deposit completed. withdraw completed »

You might also like