[Go to site: main page, start]

0% found this document useful (0 votes)
13 views39 pages

Java Chapter 4 Notes

Chapter 4 of the Java Programming document covers I/O programming, detailing the differences between text and binary files, and the classes used for reading and writing data. It explains the use of InputStream and OutputStream for binary I/O, as well as the DataInputStream and DataOutputStream for handling primitive types. Additionally, it discusses multithreading in Java, including thread life cycles, methods, and the implementation of the Runnable interface.

Uploaded by

Subrahmanya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views39 pages

Java Chapter 4 Notes

Chapter 4 of the Java Programming document covers I/O programming, detailing the differences between text and binary files, and the classes used for reading and writing data. It explains the use of InputStream and OutputStream for binary I/O, as well as the DataInputStream and DataOutputStream for handling primitive types. Additionally, it discusses multithreading in Java, including thread life cycles, methods, and the implementation of the Runnable interface.

Uploaded by

Subrahmanya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

CHAPTER 4
I/O Programming

FILES
1. Files can be classified as either text or binary
Human readable files are text files
All other files are binary files
2. Java provides many classes for performing textI/O and binary I/O

Remember, a Fileobject encapsulates the properties of afile or a path, but does not
contain the methods for reading/writing data from/to a file
In order to perform I/O, you need to create objects usingappropriate Java I/O classes
The objects contain the methods for reading/writing datafrom/to a file
Text I/O
Use the Scannerclass for reading text data from a file
The JVM converts a file specific encoding when to Unicode when reading a character
Use the PrintWriter class for writing text data to a file
The JVM converts Unicode to a file specific encoding when writing acharacter

BINARY I/O
Binary I/O does not involve encoding or decodingand thus is more efficient than text I/O
Binary files are independent of the encodingscheme on the host machine

When you write a byte to a file, the original byte is copied into the file. When you read a
byte from a file, theexact byte in the file is returned.
The abstract InputStream is the root class forreading binary data
JAVA PROGRAMMING
The abstract OutputStream is the root class forwriting binary data

The InputStreamclass

[Link]
The value returned is a
+read(): int
byte as an int type
+read(b: byte[]): int

+read(b: byte[], off: int,len:


int): int
+available(): int
+close(): void
+skip(n: long): long

+markSupported(): boolean
+mark(readlimit: int): void
+reset(): void

Reads the next byte of data from the input stream. The value byte is returned as an
int value in the range 0 to 255. If no byte is available because the end of the stream
has been reached, the value –1 is returned.
Reads up to [Link] bytes into array b from the input stream and returns theactual
number of bytes read. Returns -1 at the end of the stream.
JAVA PROGRAMMING
Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1].
The actual number of bytes read is returned. Returns -1 at theend of the stream.
Returns the number of bytes that can be read from the input stream.
Closes this input stream and releases any system resources associated with the
stream.
Skips over and discards n bytes of data from this input stream. The actualnumber of
bytes skipped is returned.
Tests if this input stream supports the mark and reset [Link] the current
position in this input stream.

Repositions this stream to the position at the time the mark method was lastcalled
on this input stream.

The InputStreamclass
[Link] The value is a byte as an int type

+write(int b): void Writes the specified byte to this output stream. The
parameter b is an int value (byte) b is written to the
+write(b: byte[]): void output stream.

+write(b: byte[], off: int, Writes all the bytes in array b to the output stream.
len: int): void Writes b[off], b[off+1],…, b[off+len-1] into the output
stream.
+close(): void
Closes this output stream and releases any system
+flush(): void resources associated with thestream.
Flushes this output stream and forces any buffered
output bytes to be written out.

The FileInputStream class


To construct a FileInputStreamobject, usethe following constructors
public FileInputStream(String filename)
public FileInputStream(File file)
A [Link] if you attempt to create a FileInputStream with a
non-existent file
JAVA PROGRAMMING

The FileInputStream class


To construct a FileOutputStreamobject, use the followingconstructors
public FileOutputStream(String filename)
public FileOutputStream(File file)
public FileOutputStream(String filename, boolean append)
public FileOutputStream(File file, boolean append)
If the file does not exist, a new file will be created
If the file already exists, the first two constructors will delete the current contents in the
file.
To retain the current content and append new data into thefile, use the last two
constructors by passing true to the append parameter

Binary file I/O using FileInputStream and FileOutputStream


public class TestFileStream
{
public static void main(String[] args) throws IOException
{
try (
FileOutputStream output = new FileOutputStream("[Link]");
)
{
for( int i=0; i<=10; i++)
[Link](i);
}
try (
{
FileInputStream input = new FileInputStream ("[Link]");
) {
int value;
While((value == [Link]()) != -1)
[Link](value + “ ”);
}
}
}
Filter Stream

FileInputStreamprovides a readmethodthat can only be used for reading bytes


If you want to read integers, doubles, or strings,you need a filter class to wrap the
byte input stream
Filter streams are streams that filter bytes forsome purpose
Using a filter class enables you to read integers,doubles, and strings instead of bytes
and characters
JAVA PROGRAMMING

The DataInputStream Class

DataInputStream reads bytes from the stream and convertsthem into appropriate primitive
type values or strings.

DataInputStream extends FilterInputStream andimplements the DataInputinterface.

The DataOutputStream Class

DataOutputStreamconverts primitive type values or strings into bytes and output the bytes
to the stream.

DataOutputStreamextends FilterOutputStreamand implements the


DataOutputinterface
JAVA PROGRAMMING

Character and String in Binary I/O

Remember, a Unicode character consists of two bytes


 The writeChar(char c)method writes the Unicode ofcharacter cto the output.
 The writeChars(String s)method writes the Unicode for each character in the string s
to the output

Remember, an ASCII character consists of one byte, whichis stored in the lower byte of a
Unicode character
 The writeByte(int v)method writes the lowest byte ofinteger v to the output (i.e., the
higher three bytes of the integer are discarded)
 The writeBytes(String s)method writes the lower byteof the Unicode of the
characters in the string s to the output (i.e., the higher byte of the Unicode of the
characters are discarded)

Unicode Transformation Format (UTF)


 The writeUTF(String s)method writes thestring sin UTF
 UTF is coding scheme for efficiently compressing astring of Unicode characters

Binary file I/O using DataInputStream and DataOutputStream

public class TestDataStream {


public static void main(String[]
args) throws IOException {try (
// Create an output stream for
file [Link]
DataOutputStream output =
new DataOutputStream(new FileOutputStream("[Link]"));
) {
[Link]("John");
[Link](85.5);
[Link]("Jim");
[Link](185.5);
[Link]("George");
[Link](105.25);
}
try (
DataInputStream input = new DataInputStream(new
FileInputStream("[Link]"));
) {
[Link]([Link]() + " " + [Link]());
JAVA PROGRAMMING
[Link]([Link]() + " " + [Link]());
[Link]([Link]() + " " + [Link]());
}
}
}

END OF FILE
If you keep reading data at the end of an InputStream, then an EOFException will occur
public class DetectEndOfFile {
public static void main(String[] args) {
try {
try (DataInputStream input =
new DataInputStream(new FileInputStream("[Link]"))) {while (true)
[Link]([Link]());
}
}
Use [Link]() tocheck for
catch (EOFException ex) {
EOF (if [Link]() == 0,
[Link]("All data were read");
then it is EOF)
}
catch (IOException ex) {
[Link]();
}
}

Binary Filter I/O Classes


Use BufferedInputStream and BufferedOutputStream tospeed up input and output by reading
ahead and writing later.
All the methods in BufferedInputStream and
BufferedOutputStreamare inherited from their superclasses

The BufferedInputStream and BufferedOutputStream Classes

// Create a BufferedInputStream
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize) The default buffer
size is 512 bytes
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out)
JAVA PROGRAMMING
public BufferedOutputStream(OutputStream out, int bufferSize)

Objects
ObjectInputStream and ObjectOutputStream can be used to read andwrite serializable
objects
Random access
RandomAccessFile allows data to be read fromand written to any location (not
necessarily sequentially) in the file
This class is used for reading and writing to random access file. A random 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 operations. If end-of-file is reached before the desired
number of byte has been read than EOFException is thrown. It is a type of IOException.

Constructor Description
RandomAccessFile(File file, String Creates a random access file stream to read from, and
mode) optionally to write to, the file specified by the File argument.

RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.

Methods of RandomAccessFiles

Modifier and Method Method


Type
void close() It closes this random access file stream and releases any
system resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel
object associated with this file.
int readInt() It reads a signed 32-bit integer from this file.
String readUTF() It reads in a string from this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning
of this file, at which the next read or write occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then writes
that long value to the file as an eight-byte quantity, high
byte first.
JAVA PROGRAMMING
void writeFloat(float v) It converts the float argument to an int using the
floatToIntBits method in class Float, and then writes that int
value to the file as a four-byte quantity, high byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning
of this file, at which the next read or write occurs.

Multithreading in Java
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the same time making optimal
use of the available resources especially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.

Thread Life Cycle and Methods


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.
JAVA PROGRAMMING
 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 terminate

Methods

1. start() - The start method initiates the execution of a thread.


2. currentThread() - The currentThread method returns the reference to the currently
executing thread object.
3. run() - The run method triggers an action for the thread.
4. isAlive() - The isAlive method is invoked to verify if the thread is alive or dead.
5. sleep() - The sleep method is used to suspend the thread temporarily.
6. yield() - The yield method is used to send the currently executing threads to standby
mode and runs different sets of threads on higher priority.
7. suspend() - The suspend method is used to instantly suspend the thread execution.
8. resume() - The resume method is used to resume the execution of a suspended thread
only.
9. interrupt() - The interrupt method triggers an interruption to the currently executing
thread class.
10. destroy() - The destroy method is invoked to destroy the execution of a group of
threads.
11. stop() - The stop method is used to stop the execution of a thread.

Example for MultiThreading


A multi-threaded program contains two or more parts that can run concurrently and each
part can handle a different task at the same time making optimal use of the available
resources.
JAVA PROGRAMMING
[Link] (Thread No. 1)

[Link] (Thread No. 2)

[Link] (Main Thread)

Output
JAVA PROGRAMMING

Runnable Interface
[Link] is an interface that is to be implemented by a class whose
instances are intended to be executed by a thread. There are two ways to start
a new Thread – Subclass Thread and implement Runnable. There is no need of
sub-classing a Thread when a task can be done by overriding only run() method
of Runnable.

Java runnable is an interface used to execute code on a concurrent thread. It is


an interface which is implemented by any class if we want that the instances of
that class should be executed by a thread.

The runnable interface has an undefined method run() with void as return type,
and it takes in no arguments. The method summary of the run() method is given
below-

Method Description

public void run() This method takes in no arguments. When the object of a class implementing
Runnable class is used to create a thread, then the run method is invoked in
the thread which executes separately.

 The runnable interface provides a standard set of rules for the instances
of classes which wish to execute code when they are active.
 The most common use case of the Runnable interface is when we want
only to override the run method.
 When a thread is started by the object of any class which is implementing
Runnable, then it invokes the run method in the separately executing
thread.
 A class that implements Runnable runs on a different thread without sub-
classing Thread as it instantiates a Thread instance and passes itself in as
the target.
 This becomes important as classes should not be sub-classed unless there
is an intention of modifying or enhancing the fundamental behavior of the
class.
JAVA PROGRAMMING

Implementing Runnable
It is the easiest way to create a thread by implementing Runnable. One can
create a thread on any object by implementing Runnable. To implement a
Runnable, one has only to implement the run method.

public void run()

In this method, we have the code which we want to execute on a concurrent


thread. In this method, we can use variables, instantiate classes, and perform an
action like the same way the main thread does. The thread remains until the
return of this method. The run method establishes an entry point to a new
thread.

Creating a thread using Runnable Interface

Runnable runnable = new MyRunnable();

Thread thread = new Thread(runnable);


[Link]();

The thread will execute the code which is mentioned in the run() method of the
Runnable object passed in its argument.

Simple Example for Runnable Interface


public class ExampleClass implements Runnable {
@Override
public void run() {
[Link]("Thread has ended");
}
public static void main(String[] args) {
ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
[Link]();
[Link]("Hi");
}
}
JAVA PROGRAMMING

Thread Vs Runnable

There are several differences between Thread class and Runnable interface
based on their performance, memory usage, and composition.

 By extending thread, there is overhead of additional methods, i.e. they


consume excess or indirect memory, computation time, or other
resources.
 Since in Java, we can only extend one class, and therefore if we extend
Thread class, then we will not be able to extend any other class. That is
why we should implement Runnable interface to create a thread.
 Runnable makes the code more flexible as, if we are extending a thread,
then our code will only be in a thread whereas, in case of runnable, one
can pass it in various executor services, or pass it to the single-threaded
environment.
 Maintenance of the code is easy if we implement the Runnable interface.

Thread Synchronization
Synchronization in Java is the capability to control the access of multiple threads
to any shared resource.

Java Synchronization is better option where we want to allow only one thread
to access the shared resource.
JAVA PROGRAMMING

Why we use Synchronization?

The synchronization is mainly used to


1. To prevent thread interference.
2. To prevent consistency problem

Types of Synchronization
There are two 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. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor.


Every object has a lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.

From Java 5 the package [Link] contains several lock


implementations.
JAVA PROGRAMMING

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see
the example:

class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}
catch(Exception e){[Link](e);}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](100);
JAVA PROGRAMMING

}
}

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThr ead1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

Output:
5
100
10
200
15
300
20
400
25
500

Java Synchronized Method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the


lock for that object and releases it when the thread completes its task.

//example of java synchronized method


class Table
{
synchronized void printTable(int n)
{//synchronized method
JAVA PROGRAMMING

for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](400);
}
catch(Exception e){[Link](e);}
}
}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](100);
}
}
JAVA PROGRAMMING

public class TestSynchronization2


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

Exception Handling with try-catch-finally block

The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling in Java.


JAVA PROGRAMMING

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that
is why we need to handle exceptions.

Hierarchy of Java Exception classes

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
JAVA PROGRAMMING

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

public class JavaExceptionExample


{
public static void main(String args[])
{
try
JAVA PROGRAMMING

{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:/ by zero
rest of the code...

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They
are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException

3) A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result
into NumberFormatException. Suppose we have a string variable that has
characters; converting this variable into digit will cause
NumberFormatException.
String s="abc";
int i=[Link](s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException
occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.
Consider the following statements.
JAVA PROGRAMMING
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java try block


Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch block

Try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
//rest of the code
}

Syntax of Java try-finally block


Try
{
//code that may throw an exception
}
Finally
{
//rest of the code
}

Internal Working of Java try-catch block


JAVA PROGRAMMING

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:

o Prints out exception description.


o Prints the stack trace (Hierarchy of methods where the exception
occurred).
o Causes the program to terminate.

But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.

Problem without Exception Handling

public class TryCatchExample1


{
public static void main(String[] args)
{
int data=50/0; //may throw exception
[Link]("rest of the code");
}
}
Output:
Exception in thread "main" [Link]: / by zero
JAVA PROGRAMMING

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).

There might be 100 lines of code after the exception. If the exception is not
handled, all the code below the exception won't be executed.

Solution by Exception Handling

public class TryCatchExample2


{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}

Output:
[Link]: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest
of the code statement is printed.

Text IO classes
The basic objects that Java programmers use to do input and output are known
as streams, readers, and writers. Most input or output operations can also
generate exceptions, and so programmers need to know how to work with
exceptions in order to do input or output. Finally, most I/O-related classes are
in the "[Link]" package in the Java libraries. Programs that do text input or
output must therefore import this package.
JAVA PROGRAMMING

Streams
A stream is a sequence of data, from which programs can input values or into
which programs can output values. The metaphor is a stream of water flowing
through a pipe -- by opening a tap in the pipe you can receive (input) water, or
you can pump (output) your own water into the pipe. Someone else at another
position along the pipe can open their own tap to receive water you have
pumped into the pipe, or can pump water into the pipe for you to receive. In
computer terms, the people on the metaphorical pipe could be two programs
communicating over a network, a program and some files, a program and a user
at a console, etc. The water in the pipe represents the data that is being
communicated.

Streams come in two basic forms: input streams, from which a program can read
data, and output streams, into which a program can write data.

Importing the I/O Classes

The classes of objects that do input or output all come from the Java class
libraries. They are all in a package named "[Link]", which is not automatically
imported into Java programs. Thus you need to explicitly import it into any
source files you write that do input or output. The easiest way to do this is to
import the whole package, by putting the statement

import [Link].*;

at the beginning of your source file(s).

Text Input

The general strategy for doing text input is to create a reader for the input
source, and then send it read or readLine messages to input individual
JAVA PROGRAMMING

characters or lines. There are several kinds of reader that you might use, the
most common being a class named BufferedReader.

Class BufferedReader

A BufferedReader is a kind of reader that groups, or "buffers" characters as it


reads them from the underlying stream. Buffering makes reading more
efficient, and allows BufferedReader objects to deliver whole lines of text as
strings.

Creation

The most common constructor for BufferedReaders takes another


(unbuffered) reader as its parameter. This constructor initializes
a BufferedReader to read and buffer characters from the reader provided as a
parameter. To kinds of reader commonly used as this parameter
are FileReader (for reading from files) and InputStreamReader (for reading
from arbitrary input streams). Both are discussed in more detail below. For
example, here is how you might create a BufferedReader that reads from the
standard keyboard input:

InputStreamReader unbuffered = new InputStreamReader( [Link] );


BufferedReader keyboard = new BufferedReader( unbuffered );
Input

Once you have created a BufferedReader, you can read either individual
characters, or whole lines, from it.

To read a line of text, use the readLine message. This message has no
parameters. It returns a string containing the next line from
the BufferedReader. If there is no more unread text in
the BufferedReader, readLine returns null. The readLine message may throw
an IOException if it is unable to read for any reason other than being at the end
of the reader. Here is an example of reading a line from
the keyboard BufferedReader created above:

try {
String inputLine = [Link]();
if ( inputLine != null ) {
// ... process "inputLine" ...
}
else {
[Link]( "No more keyboard input." );
JAVA PROGRAMMING

}
}
catch ( IOException error ) {
[Link]( "Error reading keyboard: " + error );
}

Note that this example declares the variable that receives the input line inside
the try block. Thus that variable is only defined within the try block, and so all
processing of the input has to happen within that block. This is only one of
many ways of setting up the interaction between a readLine and the try that
handles errors it might throw. You may combine the readLine and try in other
ways in your own code when appropriate.

To read single characters from a BufferedReader, use the read message. This
message has no parameters. It returns an integer, which contains the Unicode
code for the next character from the BufferedReader. If there are no more
unread characters in the BufferedReader, read returns -1. You can cast non-
negative integers returned by read to type char for processing as characters.
The read message may throw IOExceptions if it can't read for any reason other
than being at the end of the input. For example, here is code that reads a
single character from the keyboard BufferedReader created above:

try {
int input = [Link]();
if ( input >= 0 ) {
char c = (char) input;
// ... process the input character in variable "c" ...
}
else {
[Link]( "No more keyboard input." );
}
}
catch( IOException error ) {
[Link]( "Error reading keyboard: " + error );
}
Closing a BufferedReader

When you are through using a BufferedReader, you can break your program's
connection to the underlying stream and data source by sending
the BufferedReader a close message. This message takes no parameters, and
has no return value. It may, however, throw an IOException if it cannot close
the BufferedReader for some reason. For example
JAVA PROGRAMMING

try {
[Link]();
}
catch ( IOException error ) {
[Link]( "Couldn't close keyboard reader: " + error );
}
Class InputStreamReader

As mentioned above, the constructor for BufferedReader needs another reader


as its parameter. One of the reader classes commonly used for this purpose
is InputStreamReader, which is a reader for an arbitrary input stream.

The simplest constructor for InputStreamReaders takes the stream you want to
read as its only parameter.

Java automatically provides an input stream connected to the keyboard in


variable [Link]. Use this variable as a parameter to
the InputStreamReader constructor in order to create a reader that reads text
that the user types. For example

InputStreamReader keyReader = new InputStreamReader( [Link] );


Class FileReader

Another reader class commonly used to create BufferedReaders is FileReader.


This class represents readers connected to disk files. Creating
a FileReader implicitly creates an input stream to the file.

The simplest constructor for FileReaders takes the name of the file, as a String,
as its only parameter. This constructor throws an IOException if the file does not
exist. For example, to create a FileReader connected to a file named
"[Link]", you could write

try {
FileReader textReader = new FileReader( "[Link]" );
// ... Read data from "[Link]" here ...
}
catch ( IOException error ) {
[Link]( "Error processing the text file: " + error );
}
Text Output

The general strategy for outputting text is to create a kind of writer known as
a PrintWriter connected to the place you want to send your output, and then to
JAVA PROGRAMMING

use print or println messages to output the text. The print and println messages
are exactly the ones you use to print text to the console. In fact, [Link], the
object that represents the console, is an instance of a class closely related
to PrintWriter (class PrintStream).

Class PrintWriter

PrintWriter is the simplest way to output text. This class provides the
standard print and println messages for printing textual representations of just
about every data type in Java. PrintWriter objects also intercept any exceptions
generated by the output operations and handle them internally, so that clients
needn't worry about handling I/O exceptions.

The simplest constructor for PrintWriter simply takes another writer as its only
parameter.

When you are through writing data to a PrintWriter, you should send it
a close message. This message takes no parameters and has no return return
value. It breaks the connection between a program and a PrintWriter, and
makes sure that all data sent to the PrintWriter has actually been delivered to
the data sink.

As an example, here is a fragment of code that creates a PrintWriter connected


to file "[Link]" and writes the message "Hello file" to it. This example uses
a class named FileWriter (described next) to connect to the file; all exception
handling in this example is there because the FileWriter constructor may throw
exceptions.

try {
FileWriter rawOut = new FileWriter( "[Link]" );
PrintWriter out = new PrintWriter( rawOut );
[Link]( "Hello file" );
[Link]();
}
catch ( IOException error ) {
[Link]( "Error writing to output file: " + error );
}
Class FileWriter

The easiest way to write text to a file is to create a FileWriter object connected
to the file, then create a PrintWriter connected to the FileWriter.
Like FileReader, FileWriter implicitly creates a stream connected to the file.
JAVA PROGRAMMING

The simplest constructor for FileWriter objects takes the file name, in a String,
as its only parameter. This constructor may throw an IOException if it cannot
create a writer for the file. The PrintWriter example above includes code that
creates a FileWriter connected to file "[Link]."

A Complete Example

To demonstrate Java text I/O in a more realistic context, here is a program that
builds a text file by copying text from the keyboard to the file. The program
prompts the user for the file's name, then copies all subsequent keyboard
input to the file. The program stops copying when it either detects the end of
the keyboard input, or receives a line containing only a "." (some computing
environments provide a way for users to signal the end of keyboard input, the
"." convention provides a way to end the input in systems that don't).

import [Link].*;
class TextIOExample {
public static void main( String args[] ) {

try {

BufferedReader in = new BufferedReader( new InputStreamReader(


[Link] ) );
[Link]( "Destination file name = " );
String fileName = [Link]();
PrintWriter out = new PrintWriter( new FileWriter( fileName ) );

String textLine = [Link]();


while ( textLine != null && ! [Link](".") ) {
[Link]( textLine );
textLine = [Link]();
}

[Link]();
[Link]();
}
catch ( IOException error ) {
[Link]( "Error making file:" );
[Link]( "\t" + error );
}
}
}
JAVA PROGRAMMING

Collections in JAVA
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm
JAVA PROGRAMMING

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection


extends E> c) elements in the invoking collection.

3 public boolean remove(Object It is used to delete an element from the


element) collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c) specified collection from the invoking collection.

5 default boolean removeIf(Predicate<? It is used to delete all the elements of the


super E> filter) collection that satisfy the specified predicate.

6 public boolean retainAll(Collection<?> It is used to delete all the elements of invoking


c) collection except the specified collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from the
collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.


JAVA PROGRAMMING

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the


collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection


as its source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the specified


elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
JAVA PROGRAMMING

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed.

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines
its properties.

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered


list that is used to hold the elements which are about to be processed. There are
various classes like PriorityQueue, Deque, and ArrayDeque which implements the
Queue interface.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
JAVA PROGRAMMING

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables
us to perform the operations at both the ends.

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Set Interface

Set Interface in Java is present in [Link] package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It


extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
JAVA PROGRAMMING

Introduction to JavaBeans and Network Programming

A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties,
known as getter and setter methods.

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object so that we can access this object
from multiple places. Moreover, it provides easy maintenance.

package mypack;
public class Test
{
public static void main(String args[])
{
Employee e=new Employee();//object is created
[Link]("Arjun");//setting value to the object
[Link]([Link]());
}
}

JavaBean Properties

A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define

A JavaBean property may be read, write, read-only, or write-only. JavaBean


features are accessed through two methods in the JavaBean's implementation
class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
JAVA PROGRAMMING

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean

The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to the
boilerplate code.

jsp:useBean action tag

The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object
of the Bean class is already created, it doesn't create the bean depending on the scope.
But if object of bean is not created, it instantiates the bean.

<jsp:useBean id= "instanceName" scope= "page | request | session | application"


class= "[Link]" type= "[Link]"
beanName="[Link] | <%= expression >" > </jsp:useBean>

Attributes and Usage of jsp:useBean action tag


1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session
or application. The default scope is page.
o page: specifies that you can use this bean within the JSP page. The
default scope is page.
o request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
JAVA PROGRAMMING

o session: specifies that you can use this bean from any JSP page in
the same session whether processes the same request or not. It has
wider scope than request.
o application: specifies that you can use this bean from any JSP page
in the same application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the
bean class) but it must have no-arg or no constructor and must not be
abstract.
4. type: provides the bean a data type if the bean already exists in the scope.
It is mainly used with class or beanName attribute. If you use it without
class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the
[Link]() method.

Simple example of jsp:useBean action tag

In this example, we are simply invoking the method of the Bean class.

[Link] (a simple Bean class)

package [Link];
public class Calculator
{
public int cube(int n)
{
return n*n*n;
}
}

[Link] file

<jsp:useBean id="obj" class="[Link]"/>


<%
int m=[Link](5);
[Link]("cube of 5 is "+m);
%>

Common questions

Powered by AI

Thread synchronization prevents data inconsistency by ensuring that only one thread can access a shared resource at a time. This is achieved through mechanisms like synchronized methods, synchronized blocks, and static synchronization. These methods acquire a lock on the object's monitor before accessing shared data, preventing interference and maintaining consistency between threads .

Synchronization is critical in multi-threaded Java programs because it prevents thread interference and consistency problems by controlling access to shared resources. Without synchronization, concurrent threads may interrupt each other while accessing or modifying shared data, leading to unexpected behaviors and data corruption. Synchronization mechanisms like synchronized methods and blocks ensure that only one thread can execute a critical section at a time, maintaining data integrity .

InputStreamReader and FileReader both serve as bridges between byte streams and character streams in Java. InputStreamReader is more general, converting bytes from any input stream into characters, and is often used for reading from non-file sources, such as keyboard input via System.in. FileReader, on the other hand, is specialized for reading from files, simplifying the process by directly connecting to the file as a character stream. Both can be used as inputs to BufferedReader for efficient reading .

In the Runnable interface, the run() method contains the code that a thread executes when it is active. This method serves as the entry point for all parallel execution initiated by Runnable instance threads. It ensures that the thread can operate concurrently with others by defining what the thread should do once it's started. Implementing this single method allows concurrent execution without subclassing Thread and provides more flexibility and reusability of code .

One should use a synchronized block over a synchronized method when finer-grained control over synchronization is required. Synchronized blocks allow limiting the scope of synchronization to a specific block of code, rather than entire methods, thus reducing the impact on performance and preventing unnecessary locking of the whole method. This approach is beneficial when only a part of the method manipulates shared resources, allowing concurrent execution of non-critical sections .

The Runnable interface is preferred because it allows for greater flexibility and avoids the overhead of additional methods in the Thread class, which consume extra resources. Implementing Runnable also enables the class to extend another class, as Java only allows single inheritance. Moreover, Runnable instances can be passed to various executor services or single-threaded environments, facilitating code maintenance .

BufferedReader improves performance in Java I/O operations by reading larger blocks of data into a buffer, which reduces the number of read operations from the underlying stream. This buffering allows it to deliver whole lines of text efficiently as strings, rather than reading one character at a time. BufferedReader is particularly useful for reading text effectively, minimizing the overhead involved with direct reading from streams .

In Java, each object has an intrinsic lock or monitor. When a synchronized method is called, the calling thread automatically acquires the lock for the object. This prevents any other thread from entering any synchronized methods on that object until the lock is released upon method completion. Thus, locks ensure mutually exclusive access to critical sections, preventing race conditions and ensuring data integrity in concurrent applications .

The java.util.concurrent.locks package provides more flexible and advanced synchronization mechanisms compared to traditional synchronized methods and blocks. It offers features such as lock polling, timed locks, and interruptible lock acquisition, which aren't possible with intrinsic locks. These capabilities provide greater control over concurrent applications, enabling more sophisticated interaction patterns among threads, like tries and fair ordering policies. Moreover, improved performance can be achieved with ReentrantLock, especially under high contention .

Failing to properly close a BufferedReader after use can lead to resource leaks, where file descriptors or network connections remain open unnecessarily. This can exhaust system resources, leading to slowed performance or crashes due to reaching limits on open resources. Closing the BufferedReader ensures that all buffered data is flushed and releases any underlying system resources, preventing such leaks .

You might also like