Unit-2 pt2
Unit-2 pt2
In java, 3 streams are created for us automatically. All these streams are
attached with console.
Byte Streams Java byte streams are used to perform input and output of 8-
bit bytes. Though there are many classes related to byte streams but the
most frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an
input file into an output file:
import java.io.*;
{
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
} }
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.
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close(); } } } }
import java.io.*;
try {
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
1. import java.io.*;
2. public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
UNIT III
Types of Exception
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says there
are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
3) Error
Java try-catch
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Case 3
Let's see the java finally example where exception occurs and handled.
1. throw exception;
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} }
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
} }
If you are creating your own Exception that is known as custom exception or
user-defined exception. Java custom exceptions are used to customize the
exception according to user need.
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured:
"+m);}
14.
15. System.out.println("rest of the code..."); }}
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements
Runnable interface.
public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
The join() method waits for a thread to die. In other words, it causes the
currently running threads to stop executing until the thread it joins with
completes its task.
Syntax:
public void join()throws InterruptedException
15. }}
ThreadGroup in Java
File: ThreadGroupDemo.java
Synchronization in Java
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
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
wait()
notify()
notifyAll()
1) 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.
The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception.
Method Description
2) notify() method
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
UNIT IV