




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of exceptions, exception handling, file i/o, byte streams, buffered streams, reading data from the keyboard, and multithreading in java. It includes code examples and explanations of key concepts such as try-catch blocks, throws/throw keywords, user-defined exceptions, fileinputstream, fileoutputstream, bufferedinputstream, bufferedoutputstream, and multithreading methods. Designed to help students understand and implement these concepts in java programming. It covers standard input/output streams and provides examples of reading data from files and the keyboard, as well as writing data to files. The document also touches on multithreading, explaining how to create and manage threads in java.
Typology: Study notes
1 / 28
This page cannot be seen from the preview
Don't miss anything!





















PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. An exception can occur for many different reasons. Following are some scenarios where an exception occurs. A user has entered an invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner Based on these, we have three categories of Exceptions. Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
Default Exception Handling : Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an Exception.There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack .Now the following procedure will happen. The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler. The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called. If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Something went wrong."); } } } The output will be: Something went wrong. MULTIPLE CATCH BLOCKS A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following − Syntax try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } THE THROWS/THROW KEYWORDS If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. The following method declares that it throws a RemoteException − Example import java.io.; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException − Example import java.io.; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } // Remainder of class definition } THE FINALLY BLOCK The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
Note the following − A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks.
User Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’ keyword. This can be done by extending the class Exception. There is no need to override any of the above methods available in the Exception class, in your derived class. But practically, you will require some amount of customizing as per your programming needs. Example: class MyException extends Exception { String s1; MyException(String s2) { s1 = s2; } public String toString() { return ("Output String = "+s1); } } public class NewClass { public static void main(String args[]) { try { throw new MyException("Custom message"); } catch(MyException exp) { System.out.println(exp); } } } Result The above code sample will produce the following result. Output String = Custom message
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc. STREAM A stream can be defined as a sequence of data. There are two kinds of Streams − InPutStream − The InputStream is used to read data from a source. OutPutStream − The OutputStream is used for writing data to a destination. In Java, 3 streams are created for us automatically. All these streams are attached with the console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content − This is test for copy file. As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following − $javac CopyFile.java $java CopyFile CHARACTER STREAMS Java Byte streams are used to perform input and output of 8 - bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file − Example import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null;
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != - 1 ) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let's have a file input.txt with the following content − This is test for copy file. As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following − $javac CopyFile.java $java CopyFile STANDARD STREAMS All the programming languages provide support for standard I/O where the user's program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program. This program continues to read and output the same character until we press 'q' − $javac ReadConsole.java $java ReadConsole Enter characters, 'q' to quit. 1 1 e e q q READING AND WRITING FILES As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams. The two important streams are FileInputStream and FileOutputStream , which would be discussed in this tutorial.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available. Following constructor takes a file name as a string to create an input stream object to read the file − InputStream f = new FileInputStream("C:/java/hello"); Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows − File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f); Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream. Sr.No. Method & Description 1 public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. 2 protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. 3 public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and - 1 will be returned if it's the end of the file. 4 public int read(byte[] r) throws IOException{} This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, - 1 will be returned. 5 public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. Returns an int.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
public class fileStreamTest { public static void main(String args[]) { try { byte bWrite [] = { 11 , 21 , 3 , 40 , 5 }; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0 ; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i = 0 ; i < size; i++) { System.out.print((char)is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); } } } The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast. The important points about BufferedInputStream are:
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
o When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time. o When a BufferedInputStream is created, an internal buffer array is created. Java BufferedInputStream class declaration Let's see the declaration for Java.io.BufferedInputStream class: public class BufferedInputStream extends FilterInputStream Java BufferedInputStream class constructors Constructor Description BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the input stream IS, for later use. BufferedInputStream(InputStream IS, int size) It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use. Java BufferedInputStream class methods Method Description int available() It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream. int read() It read the next byte of data from the input stream. int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset. void close() It closes the input stream and releases any of the system resources
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
Java BufferedOutputStream Class Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream: OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\IO Package\testo ut.txt")); Java BufferedOutputStream class declaration Let's see the declaration for Java.io.BufferedOutputStream class: public class BufferedOutputStream extends FilterOutputStream Java BufferedOutputStream class constructors Constructor Description BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to the specified output stream. BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size. Java BufferedOutputStream class methods Method Description void write(int b) It writes the specified byte to the buffered output stream.
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS^ BATCH
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset void flush() It flushes the buffered output stream. Example of BufferedOutputStream class : In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another. package com.javatpoint; import java.io.*; public class BufferedOutputStreamExample{ public static void main(String args[]) throws Exception{ FileOutputStream fout= new FileOutputStream("D:\testout.txt"); BufferedOutputStream bout= new BufferedOutputStream(fout); String s="Welcome to javaTpoint."; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close(); fout.close(); System.out.println("success"); } } Output: Success READING DATA FROM KEYBOARD There are many ways to read data from the keyboard. For example: InputStreamReader Console