Java 4 and 5th Unit Notes - 064815
Java 4 and 5th Unit Notes - 064815
Before exploring various input and output streams lets look at 3 standard or default
streams that Java has to provide which are also most common in use:
1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
print(): This method in Java is used to display a text on the console. This text is passed
as the parameter to this method in the form of String. This method prints the text on the
console and the cursor remains at the end of the text at the console. The next printing
takes place from just here.
Syntax:
System.out.print(parameter);
class Demo_print {
public static void main(String[] args)
{
// using print() all are printed in the same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
Example:
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple"+ " integer: x = %d\n",x);
float n = 5.2f;
class Demo_print {
public static void main(String[] args)
{
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take
multiple arguments. This is used to format the output in Java.
Example:
// A Java program to demonstrate working of printf() in Java
class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing simple"+ " integer: x = %d\n",x);
System.out.printf("Formatted with"+ " precision: PI = %.2f\n",Math.PI);
float n = 5.2f;
System.out.printf("Formatted to "+ "specific width: n = %.4f\n",n);
n = 2324435.3f;
System.out.printf("Formatted to "+ "right margin: n = %20.4f\n",n);
}
}
2. System.err: This is the standard error stream that is used to output all the error data that
a program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
print()
println()
printf()
Types of Streams:
Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from a source
array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array or file or any
output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
Depending on the types of file, Streams can be divided into two primary classes which can be
further divided into other classes:
1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes,
the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream
is used to read from the source and FileOutputStream is used to write to the destination. Here is
the list of various ByteStream Classes:
2. CharacterStream: In Java, characters are stored using Unicode conventions (Refer this
for details). Character stream automatically allows us to read/write data character by
character. Though it has many classes, the FileReader and the FileWriter are the most popular
ones. FileReader and FileWriter are character streams used to read from the source and write
to the destination respectively. Here is the list of various CharacterStream Classes:
Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be
used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.
Constructor Description
BufferedReader(Reader rd) It is used to create a buffered character input stream that uses the default size
for an input buffer.
BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses the specified size
size) for an input buffer.
Method Description
int read(char[] cbuf, int off, int It is used for reading characters into a portion of an array.
len)
boolean ready() It is used to test whether the input stream is ready to be read.
void close() It closes the input stream and releases any of the system resources associated
with the stream.
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
Class declaration
Class constructors
Constructor Description
BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the default size
for an output buffer.
BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses the specified
size) size for an output buffer.
Class methods
Method Description
void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.
void write(String s, int off, int len) It is used to write a portion of a string.
import java.io.*;
//initializing FileWriter
FileWriter geek_file;
try
// Initializing BufferedWriter
geekwrite.write(69);
// Printing 1
geekwrite.write(49);
geekwrite.close();
System.out.println("Written successfully");
except.printStackTrace();
} } }
FileWriter
FileWriter is useful to create a file writing characters into it.
Constructors:
FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
Methods:
public void write (char [] stir) throws IOException – Writes an array of characters.
public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here
off is offset from which to start writing characters and len is the number of characters to write.
public void flush() throws IOException flushes the stream
public void close() throws IOException flushes the stream first and then closes the writer.
Reading and writing take place character by character, which increases the number of I/O
operations and affects the performance of the system.BufferedWriter can be used along with
FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
// attach a file to FileWriter
FileWriter fw=new FileWriter("output.txt");
System.out.println("Writing successful");
//close the file
fw.close();
}
}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
Methods:
public int read () throws IOException – Reads a single character. This method will block
until a character is available, an I/O error occurs, or the end of the stream is reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array. This
method will block until some input is available, an I/O error occurs, or the end of the stream
is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters
into a portion of an array. This method will block until some input is available, an I/O error
occurs, or the end of the stream is reached.
Parameters:
public long skip(long n) throws IOException –Skips characters. This method will block until some
characters are available, an I/O error occurs, or the end of the stream is reached.
Parameters:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;
This class gives Prints formatted representations of objects to a text-output stream. It implements
all of the print methods found in PrintStream. It does not contain methods for writing raw bytes,
for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of
the println, printf, or format methods is invoked, rather than whenever a newline character
happens to be output. These methods use the platform’s own notion of line separator rather than
the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The
client may inquire as to whether any errors have occurred by invoking checkError().
A file is aabstract data type. A named location used to store related information is known as a File.
There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.
Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.
Stream
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a
process in which an input is provided and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a character
stream is a process in which an input is provided and executed with the character data.
1. canRead() Boolean The canRead() method is used to check whether we can read the
data of the file or not.
2. createNewFile() Boolean The createNewFile() method is used to create a new empty file.
3. canWrite() Boolean The canWrite() method is used to check whether we can write the
data into the file or not.
4. exists() Boolean The exists() method is used to check whether the specified file is
present or not.
6. getName() String The getName() method is used to find the file name.
7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute pathname
of the file.
8. length() Long The length() method is used to get the size of the file in bytes.
9. list() String[] The list() method is used to get an array of the files available in the
directory.
10. mkdir() Boolean The mkdir() method is used for creating a new directory.
File Operations
We can perform the following operation on a file:
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File
Create a File operation is performed to create a new file. We use the createNewFile() method of
file. The createNewFile() method returns true when it successfully creates a new file and returns
false when the file already exists.
Get File Information
The operation is performed to get the file information. We use several methods to get the
information about the file like name, absolute path, is readable, is writable and length.
Write to a File
The next operation which we can perform on a file is "writing into a file". In order to write data
into a file, we will use the FileWriter class and its write() method together. We need to close the
stream using the close() method to retrieve the allocated resources.
The next operation which we can perform on a file is "read from a file". In order to write data
into a file, we will use the Scanner class. Here, we need to close the stream using
the close() method. We will create an instance of the Scanner class and use
the hasNextLine() method nextLine() method to get data from the file.
Delete a File
The next operation which we can perform on a file is "deleting a file". In order to delete a file,
we will use the delete() method of the file. We don't need to close the stream using
the close() method because for deleting a file, we neither use the FileWriter class nor the Scanner
class.
The reverse operation of serialization is called deserialization where byte-stream is converted into
an object. The serialization and deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for
deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by
default.
Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream. The main class implementation of is showed in the next code.
In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object. We are saving the state of the object in the file named f.txt.
import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization. Let's see an example where we are reading the data from a deserialized
object.
Depersist.java
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
Unit 5 Multithreading
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Thread in java
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread objec
15) Void destroy() It is used to destroy the thread group and all of its subgroup
How to create a thread in Java
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.
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
FileName: Multi.java
FileName: Multi3.java
If you are not extending the Thread class, your class object would not be treated as a thread object.
So you need to explicitly create the Thread class object. We are passing the object of your class
that implements Runnable so that your class run() method may execute.
We can directly use the Thread class to spawn new threads using the constructors defined above.
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. The following diagram shows the complete life cycle of a thread.
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent.
Syntax
1. public final boolean isAlive()
Return
This method will return true if the thread is alive otherwise returns false.
Example
1. public class JavaIsAliveExp extends Thread
2. {
3. public void run()
4. {
5. try
6. {
7. Thread.sleep(300);
8. System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
9. }
10. catch (InterruptedException ie) {
11. }
12. }
13. public static void main(String[] args)
14. {
15. JavaIsAliveExp t1 = new JavaIsAliveExp();
16. System.out.println("before starting thread isAlive: "+t1.isAlive());
17. t1.start();
18. System.out.println("after starting thread isAlive: "+t1.isAlive());
19. }
20. }
Java join() method
The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait
until the other thread to finish its execution. Suppose th be the object the class Thread whose thread
is doing its execution currently, then the th.join(); statement ensures that th is finished before the
program does the execution of the next statement. When there are more than one thread invoking
the join() method, then it leads to overloading on the join() method that permits the developer or
programmer to mention the waiting period.
import java.io.*;
import java.util.*;
th2.start();
th3.start();
}
}
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues. For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one thread is opening the
same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
1. class Table {
2. synchronized void printTable(int n){//synchronized method
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. public class TestSynchronization2{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }
wait()
notify()
notifyAll()
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.
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
public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException 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.
3) notifyAll() method
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Example of Inter Thread Communication in Java
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }
Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. t2.suspend(); // suspend t2 thread
26. // call run() method
27. t3.start();
28. t2.resume(); // resume t2 thread
29. }
30. }
Example
1. public class JavaStopExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaStopExp t1=new JavaStopExp ();
20. JavaStopExp t2=new JavaStopExp ();
21. JavaStopExp t3=new JavaStopExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // stop t3 thread
26. t3.stop();
27. System.out.println("Thread t3 is stopped");
28. }
29. }