Java Unit 4
Java Unit 4
I/O programming Java application uses an input stream to read data from a source; it may be
a file, an array, peripheral device or socket.
Java I/O (Input and Output) is used to process the input and produce the
output. Let's understand the working of Java OutputStream and InputStream by
b
the figure given below.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
Stream
2) System.in: standard input stream OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output
3) System.err: standard error stream bytes and sends them to some sink.
OutputStream Hierarchy
3) public void close()throws is used to close the current input stream.
IOException
InputStream Hierarchy
Output:
Success...
testout.txt
syntax for adding the buffer in an OutputStream: Java BufferedOutputStream class methods
Java BufferedOutputStream class declaration void write(int b) It writes the specified byte to the buffered output
stream.
Let's see the declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream void write(byte[] b, It write the bytes from the specified byte-input
int off, int len) stream into a specified byte array, starting with the
Java BufferedOutputStream class constructors given offset
In this example, we are writing the textual information in the Java BufferedInputStream class is used to read information from stream. It
BufferedOutputStream object which is connected to internally uses buffer mechanism to make the performance fast.
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 The important points about BufferedInputStream are:
stream with another.
o When the bytes from the stream are skipped or read, the internal
import java.io.*; buffer automatically refilled from the contained input stream, many
public class BufferedOutputStreamExample{ bytes at a time.
public static void main(String args[])throws Exception{ o When a BufferedInputStream is created, an internal buffer array is
FileOutputStream fout=new FileOutputStream("D:\\testout.txt"); created.
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java I/O Programing."; Java BufferedInputStream class declaration
byte b[]=s.getBytes();
bout.write(b); public class BufferedInputStream extends FilterInputStream
bout.flush();
bout.close(); Java ByteArrayOutputStream Class
fout.close();
System.out.println("success"); Java ByteArrayOutputStream class is used to write common data into
} multiple files. In this stream, the data is written into a byte array which can
} be written to multiple streams later.
public class ByteArrayOutputStream extends OutputStream ObjectStreamField[] getFields() It returns an array of the
fields of this serialization
Java - ObjectStreamClass class.
ObjectStreamClass act as a Serialization descriptor for class. String getName() It returns the name of the
This class contains the name and serialVersionUID of the class.
class described by this
descriptor.
Fields
Modifier and Type Field Description
long getSerialVersionUID() It returns the
serialVersionUID for this
static NO_FIELDS serialPersistentFields value class.
ObjectStreamField[] indicating no serializable fields
Static lookup(Class<?> cl) It finds the descriptor for a
ObjectStreamClass class that can be serialized.
Methods
Modifier and Method Description
Static lookupAny(Class<?> It returns the descriptor for
Type
ObjectStreamClass cl) any class, regardless of
whether it implements
Class<?> forClass() It returns the class in the Serializable.
local VM that this version
is mapped to. String toString() It returns a string
describing this
ObjectStreamClass. Output:
I price
Null
Example
Java - RandomAccessFile
import java.io.ObjectStreamClass;
This class is used for reading and writing to random access file. A random
import java.util.Calendar;
access file behaves like a large array of bytes. There is a cursor implied to
the array called file pointer, by moving the cursor we do the read write
public class ObjectStreamClassExample { operations. If end-of-file is reached before the desired number of byte has
public static void main(String[] args) { been read than EOFException is thrown. It is a type of IOException.
// get the value field from ObjectStreamClass for integers RandomAccessFile(File Creates a random access file stream to
System.out.println("" + osc.getField("price")); file, String mode) read from, and optionally to write to, the
file specified by the File argument.
// create a new object stream class for Calendar
ObjectStreamClass osc2 = ObjectStreamClass.lookup(String.class); RandomAccessFile(String Creates a random access file stream to
name, String mode) read from, and optionally to write to, a
// get the Class instance for osc2 file with the specified name.
System.out.println("" + osc2.getField("hash"));
}
Multithreading in Java
}
Multithreading in Java is a process of executing multiple threads 1) Process-based Multitasking (Multiprocessing)
simultaneously.
o Each process has an address in memory. In other words, each
A thread is a lightweight sub-process, the smallest unit of processing. process allocates a separate memory area.
Multiprocessing and multithreading, both are used to achieve multitasking. o A process is heavyweight.
However, we use multithreading than multiprocessing because threads use o Cost of communication between the process is high.
a shared memory area. They don't allocate separate memory area so saves o Switching from one process to another requires some time for
memory, and context-switching between the threads takes less time than saving and loading registers, memory maps, updating lists, etc.
process.
Java Multithreading is mostly used in games, animation, etc. 2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
Advantages of Java Multithreading o A thread is lightweight.
1) It doesn't block the user because threads are independent and you can o Cost of communication between the thread is low.
perform multiple operations at the same time.
Note: At least one process is required for each thread.
2) You can perform many operations together, so it saves time.
What is Thread in java
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread. A thread is a lightweight subprocess, the smallest unit of processing. It is a
separate path of execution.
Multitasking
Threads are independent. If there occurs exception in one thread, it doesn't
Multitasking is a process of executing multiple tasks simultaneously. We affect other threads. It uses a shared memory area.
use multitasking to utilize the CPU. Multitasking can be achieved in two
ways:
FileName: Multi3.java
Java Threads | How to create a thread in Java class Multi3 implements Runnable{
public void run(){
There are two ways to create a thread: System.out.println("thread is running...");
}
1. By extending Thread class public static void main(String args[]){
2. By implementing Runnable interface. Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
1) Java Thread Example by extending Thread class
t1.start();
FileName: Multi.java } }
Explanation of Different Thread States Terminated: A thread reaches the termination state because of the
following reasons:
New: Whenever a new thread is created, it is always in the new state. For
a thread in the new state, the code has not been run yet and thus has not o When a thread has finished its job, then it exists or terminates
begun its execution.
normally.
o Abnormal termination: It occurs when some unusual events such public void sleep(long miliseconds): Causes the currently executing
as an unhandled exception or segmentation fault. thread to sleep (temporarily cease execution) for the specified number
of milliseconds.
A terminated thread means the thread is no more in the system. In other
words, the thread is dead, and there is no way one can respawn (active
public void join(): waits for a thread to die.
after kill) the dead thread.
Thread class: public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements public int getPriority(): returns the priority of the thread.
Runnable interface.
public int setPriority(int priority): changes the priority of the thread.
Commonly used Constructors of Thread class:
public String getName(): returns the name of the thread.
o Thread()
o Thread(String name) public void setName(String name): changes the name of the thread.
o Thread(Runnable r)
public Thread currentThread(): returns the reference of currently
o Thread(Runnable r,String name)
executing thread.
Commonly used methods of Thread class:
public int getId(): returns the id of the thread.
public void run(): is used to perform action for a thread.
public Thread.State getState(): returns the state of the thread.
public void start(): starts the execution of the thread.JVM calls the
public boolean isAlive(): tests if the thread is alive.
run() method on the thread.
public void resume(): is used to resume the suspended The start() method of Thread class is used to start a newly created thread.
It performs the following tasks:
thread(depricated).
o A new thread starts(with new callstack).
public void stop(): is used to stop the thread(depricated).
o The thread moves from New state to the Runnable state.
public boolean isDaemon(): tests if the thread is a daemon thread. o When the thread gets a chance to execute, its target run() method
will run
public void setDaemon(boolean b): marks the thread as daemon or
user thread. Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-
public void interrupt(): interrupts the thread.
thread communication.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) Protocol
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts ArrayList (Simple Collection Program)
as a communication endpoint between applications.
The ArrayList class implements the List interface. It uses a dynamic array
The port number is associated with the IP address for communication to store the duplicate element of different data types. The ArrayList class
between two applications. maintains the insertion order and is non-synchronized. The elements stored
in the ArrayList class can be randomly accessed. Consider the following
4) MAC Address example.
MAC (Media Access Control) address is a unique identifier of NIC import java.util.*;
(Network Interface Controller). A network node can have multiple NIC class TestJavaCollection1{
but each with unique MAC address.
public static void main(String args[]){
For example, an ethernet card may have a MAC address of ArrayList<String> list=new ArrayList<String>();//Creating arraylist
00:0d:83::b1:c0:8e. list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
5) Connection-oriented and connection-less protocol list.add("Ravi");
list.add("Ajay");
In connection-oriented protocol, acknowledgement is sent by the receiver. //Traversing list through Iterator
So it is reliable but slow. The example of connection-oriented protocol is
Iterator itr=list.iterator();
TCP.
while(itr.hasNext()){
But, in connection-less protocol, acknowledgement is not sent by the System.out.println(itr.next());
receiver. So it is not reliable but fast. The example of connection-less }
protocol is UDP. }
}
6) Socket
Output:
A socket is an endpoint between two way communications.
Ravi Vijay Ravi Ajay
Hierarchy of Collection Framework 1) What is stream? Types of streams
Let us see the hierarchy of Collection framework. The java.util package 2) What is thread? Difference between multithread and multitasking?
contains all the classes and interfaces for the Collection framework.
3) Explain Thread lifecycle with diagram?
4) What is collection?
8) Thread Program
Important questions