OOP java-unit 2
OOP java-unit 2
UNIT-II
JAVA I/O TUTORIAL
Java I/O (Input and Output) is used to process the input and produce the
output.
Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
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
class CopyFile {
{
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 {
char c;
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();
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){}
3. try{
4. int data=50/0;
5. }catch(ArithmeticException e){System.out.println(e);}
6. System.out.println("rest of the code...");
7. }
8. }
Java Multi catch block
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.
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
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.
2. InvalidAgeException(String s){
3. super(s);
4. }
5. }
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..."); }}
Stops the current flow of execution It forces the caller to handle the
Flow of Execution immediately. declared exceptions.
Objects, specifically by
Variables, methods, and Only within a try-
Can be used overriding the method
classes. catch block.
with in a class
final Keyword
The final keyword in Java is used with variables, methods, and also with classes to restrict modification.
Syntax:
// Constant value
final int a = 100;
Example: The below Java program demonstrates the value of the variable cannot be changed once
initialized.
// final variable
final int b = 6;
Note: If we declare any variable as final, we can’t modify its contents since it is final, and if we modify it
then we get Compile Time Error.
In the above example, we used the final keyword to declare a variable that cannot be modified after its
initialization. Similarly, the final keyword can also be applied to methods and classes in Java to
impose certain restrictions.
finally Keyword
The finally keyword in Java is used to create a block of code that always executes after the try block,
regardless of whether an exception occurs or not.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example: The below Java program demonstrates the working of finally block in exception handling.
// Java program to demonstrate
// the working of finally block
public class Geeks {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");
int result
= 10 / 0; // This will cause an exception
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
}
catch (ArithmeticException e) {
System.out.println("Exception caught: "
+ e.getMessage());
}
finally {
System.out.println(
"finally block always execute");
}
}
}
Output:
Explanation: The try block attempts a division by zero, causing an ArithmeticException. The finally block
executes, whether an exception occurs, ensuring cleanup or mandatory code execution.
finalize() Method
The finalize() method is called by the Garbage Collector just before an object is removed from memory. It
allows us to perform clean up activity. Once the finalized method completes, Garbage Collector destroys
that object.finalize method is present in the Object class.
Syntax:
protected void finalize throws Throwable{}
Example: The below Java program demonstrates the working of finalize() method in context of garbage
collection.
// Java Program to demonstrates
// the working of finalize() Method
import java.util.*;
System.gc();
Explanation: In the above example, an object “g” is created, and its hash code is printed. The object is
made eligible for garbage collection by setting it to null and invoking System.gc().
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
SABIYA FATIMA, ASSISTANT PROFESSOR, CSE
AXIS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
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:
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
InterruptedException
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
14. try{
15. t1.join();
16. }catch(Exception e){System.out.println(e);}
17. t2.start();
18. t3.start();
19. } }
15. }}
ThreadGroup in Java
ThreadGroup Example
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
Method Description
2) notify() method
3) notifyAll() method