0% found this document useful (0 votes)
16 views58 pages

Programming in Java - Unit III

Uploaded by

cs235114110
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)
16 views58 pages

Programming in Java - Unit III

Uploaded by

cs235114110
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
You are on page 1/ 58

Programming in Java

Unit III
Unit III
Multithreaded Programming: Thread Class – Runnable Interface –
Synchronization – Using Synchronized methods – Using Synchronized
statement – Interthread Communication – Deadlock.
I/O Streams: Concepts of streams – Stream Classes – Byte and
Character stream – Reading console Input and Writing Console output –
File Handling

U23CA404 - Programming in Java 2


Multithreaded Programming
• Multithreading in Java is a process of executing multiple threads
simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
• Multiprocessing and multithreading, both are used to achieve
multitasking.
• However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less time
than process.
• Java Multithreading is mostly used in games, animation, etc.

U23CA404 - Programming in Java 3


Multithreading Vs Multiprocessing
• Multitasking is a process of executing multiple tasks simultaneously.
• It is used to utilize the CPU.
• Multitasking can be achieved in two ways:
• Process-based multitasking – Multiprocessing
• Thread-based multitasking - Multithreading

Multiprocessing Multithreading
Each process has an address in memory. In other
words, each process allocates a separate memory Threads share the same address space.
area.

A process is heavyweight. A thread is lightweight.

Cost of communication between the process is Cost of communication between the thread is
high. low.

Switching from one process to another requires


some time for saving and loading registers,
memory maps, updating lists, etc.

U23CA404 - Programming in Java 4


Life Cycle of Thread

U23CA404 - Programming in Java 5


Life Cycle of a Thread
State Description Implementing Thread States
New When a new thread is created, it is in the new state. The thread has not public static final Thread.State NEW
yet started to run when the thread is in this state. When a thread lies in
the new state, its code is yet to be run and hasn’t started to execute.
Runnable The thread is ready for execution and is waiting for the availability of public static final Thread.State
the processor. i.e in QUEUE manner. RUNNABLE
If all the thread have equal priority, it will be executed in round robin
fashion i.e., FCFS manner
Blocked The thread will be in blocked state when it is trying to acquire a lock public static final Thread.State BLOCKED
but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the
lock
Waiting The thread will be in waiting state when it calls wait() method or join() public static final Thread.State WAITING
method. It will move to the runnable state when other thread will
notify or that thread will be terminated.
Timed A thread lies in a timed waiting state when it calls a method with a public static final Thread.State
waiting time-out parameter. A thread lies in this state until the timeout is TIMED_WAITING
completed or until a notification is received.
Terminated A thread terminates because of either of the following reasons: public static final Thread.State
• Because it exits normally. This happens when the code of the TERMINATED
thread has been entirely executed by the program.
• Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandledU23CA404
exception.
- Programming in Java 7
Thread Class
• A thread is a lightweight subprocess, the smallest unit of processing. It is
a separate path of execution.
• Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.
• Constructors of Thread Class
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

U23CA404 - Programming in Java 8


Creating a Thread
• There are the following two ways to create a thread:
• By Extending Thread Class
• By Implementing Runnable Interface

U23CA404 - Programming in Java 9


1. By Extending Thread
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.
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

Multithreading 10
1. By Extending Thread

class Multi extends Thread //Extending thread class


{
public void run() // run() method declared
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(); //object initiated
t1.start(); // run() method called through start()
}
}
Output: thread is running…

Multithreading 11
2. By implementing Runnable interface
• Define a class that implements Runnable interface.
• The Runnable interface has only one method, run(), that is to be defined
in the method with the code to be executed by the thread.

Multithreading 12
2. By implementing Runnable interface
class Multi3 implements Runnable //Implementing Runnable interface
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3(); // object initiated for class
Thread t1 =new Thread(m1); // object initiated for thread
t1.start();
}
}
Output: thread is running…

Multithreading 13
Methods of Thread class:
Methods Description

public void run() used to perform action for a thread.

public void start() starts the execution of the thread.JVM calls the run() method on
the thread.
public void sleep(long Causes the currently executing thread to sleep (temporarily cease
miliseconds) execution) for the specified number of milliseconds.
public void join() waits for a thread to die.

public void join(long waits for a thread to die for the specified miliseconds.
miliseconds)
public int getPriority() returns the priority of the thread.

public int setPriority(int changes the priority of the thread.


priority)
public String getName() returns the name of the thread.

public void setName(String changes the name of the thread.


name)
public Thread returns the reference of currently executing thread.
currentThread()
public int getId() returns the id of the thread.
Multithreading 14
Methods of Thread class:
Methods Description

public Thread.State returns the state of the thread.


getState()
public boolean isAlive(): tests if the thread is alive.

public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
public void suspend(): used to suspend the thread(depricated).

public void resume(): used to resume the suspended thread(depricated).

public void stop(): used to stop the thread(depricated).

public boolean isDaemon(): tests if the thread is a daemon thread.

public void marks the thread as daemon or user thread.


setDaemon(boolean b):
public void interrupt(): interrupts the thread.

public boolean tests if the thread has been interrupted.


isInterrupted():
public static boolean tests if the current thread has been interrupted.
Multithreading 15
interrupted():
Static Methods in Thread Class
Syntax of the method Purpose
static Thread currentThread() To return a reference to the current thread
static void sleep(long m) To cause the current thread to wait for m milliseconds
static sleep(long m , long n) To cause the current thread to wait for m milliseconds plus n
nanoseconds

Multithreading 16
Instance methods in Thread Class
Methods Purpose
void start() To start the specific thread
void run() To encapsulate the functionality of a thread
boolean isAlive() To return true if thread has been started and not yet died
void setName(String s) To set the name of the thread to ‘s’
String getName() To return the name of the specified thread
void setPriority(int p) To Set the priority of the thread to ‘p’
int getPriority() To return the priority of the thread

Multithreading 17
Priority of a Thread
• Each thread has a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, the thread scheduler schedules the threads according to
their priority (known as preemptive scheduling).
• But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
• Note that not only JVM a Java programmer can also assign the priorities
of a thread explicitly in a Java program.

Multithreading 18
Setter & Getter Method of Thread Priority
• public final int getPriority():

• The java.lang.Thread.getPriority() method returns the priority of the given


thread.
• public final void setPriority(int newPriority):

• The java.lang.Thread.setPriority() method updates or assign the priority of the


thread to newPriority.

• The method throws IllegalArgumentException if the value newPriority goes out


of the range, which is 1 (minimum) to 10 (maximum).
Multithreading 19
3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).


The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is
10.

Multithreading 20
// Importing the required classes
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String argvs[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
// We did not mention the priority of the thread. Therefore, the priorities of the thread is 5, the
default value
// 1st Thread Displaying the priority of the thread using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
Multithreading 21
// Setting priorities of above threads by passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName()
);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}

Multithreading 22
Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

Multithreading 23
Advantages of Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.

U23CA404 - Programming in Java 24


Synchronization
• Synchronization in Java is a critical concept in concurrent programming
that ensures multiple threads can interact with shared resources safely.
• In a nutshell, synchronization prevents race conditions, where the
outcome of operations depends on the timing of thread execution.
• It is the capability to control the access of multiple threads to any shared
resource.
• Synchronization is a better option where we want to allow only one
thread to access the shared resource.

U23CA404 - Programming in Java 25


Using synchronization method and statements
• The access to a method shall be synchronized by specifying the
synchronized keyword as a modifier in the method declaration.
• When a thread starts executing a synchronized instance meyhod, it
automatically gets a logical lock on the object that contains the
synchronized method.
• This lock will remain till the thread is executing in that synchronized
method.
• When the lock is present, no other thread will be allowed entry into that
object.
• The lock will automatically released, when the thread completes its
execution.

U23CA404 - Programming in Java 26


Example Program
class Account{ class CreditDemo{
private int balance=0; static int numAccountHolders=5;
synchronized void credit(int amount){ public static void main(String args[])
balance=balance+amount; {
} Account account=new Account();
void displayBalance(){ AccountHolder accountholders[]=new AccountHolder[numAccountHolders];
System.out.println(balance); for(int k=0;k<numAccountHolders;k++)
} {
} accountholders[k]=new AccountHolders(account);
class AccountHolder extends Thread{ accountholders[k].start();
Account account; }
AccountHolder(Account account){ for(int i=0;i<numAccountHolders;i++)
this.account=account; {
} try
void run(){ {
for(int j=0;j<5000;j++) accountholders[i].join();
account.credit(100); }
} catch(Exception e){} Output:
} account.displayBalance(); 500000
} 2500000
} 2500000
} 2500000
2500000

U23CA404 - Programming in Java 27


Explanation
• In the above program, the Account class is defined with synchronized
credit() method and an ordinary method named displayBalance(). another
class AccountHolder is defined with constructor and run() method.
• With in the main() method, single instance for Account class is created
and three instances are created for AccountHolder class. i.e., three
different threads are created and started.
• These three threads access the common method credit() that is declared
with synchronized keyword.
• The main thread will wait until all these threads get executed with the
help of join() method.
• Once these three threads complete their work, the final balance is
retrieved and displayed.

U23CA404 - Programming in Java 28


Inter-thread Communication
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• Cooperation (Inter-thread communication) is a mechanism in which a
thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()

U23CA404 - Programming in Java 29


Method Syntax Description
public final void wait()throws
It waits until object is notified.
InterruptedException
wait()
public final void wait(long timeout)throws
It waits for the specified amount of time.
InterruptedException
The notify() method wakes up a single thread that is waiting on
notify() public final void notify()
this object's monitor.
notifyAll() public final void notifyAll() Wakes up all threads that are waiting on this object's monitor.

Understanding the process of inter-thread communication


1. Threads enter to acquire lock.
2. Lock is acquired by a thread.
3. Now thread goes to waiting state if you call wait() method on the
object. Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.

U23CA404 - Programming in Java 30


class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
Example synchronized void deposit(int amount){
System.out.println("going to deposit...");
Program this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{ Output:
public static void main(String args[]){ going to deposit...
final Customer c=new Customer(); deposit completed...
new Thread(){ going to withdraw...
public void run(){c.withdraw(15000);} withdraw completed...
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start(); U23CA404 - Programming in Java 31
}}
Deadlock
• Deadlock in Java is a part of multithreading.
• Deadlock can occur in a situation when a thread is waiting for an object
lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread.
• Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.

U23CA404 - Programming in Java 32


Deadlock possibilities

• A deadlock may also include more than two threads. The reason is that it
can be difficult to detect a deadlock.
• Here is an example in which four threads have deadlocked:
• Thread 1 locks A, waits for B
• Thread 2 locks B, waits for C
• Thread 3 locks C, waits for D
• Thread 4 locks D, waits for A
• Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread
4, and thread 4 waits for thread 1.

U23CA404 - Programming in Java 33


Example Program
public class DeadlockSolved { private class resource1 { // resource1
public static void main(String ar[]) { private int i = 10;
DeadlockSolved test = new DeadlockSolved(); public int getI() {
final resource1 a = test.new resource1(); return i;
final resource2 b = test.new resource2(); }
Runnable b1 = new Runnable() { // Thread-1 public void setI(int i) {
public void run() { this.i = i;
synchronized (b) { } }
try { // Adding delay so that both threads can start trying to lock resources private class resource2 { // resource2
Thread.sleep(100); private int i = 20;
} catch (InterruptedException e) { public int getI() {
e.printStackTrace(); return i;
} // Thread-1 have resource1 but need resource2 also }
synchronized (a) { public void setI(int i) {
System.out.println("In block 1"); this.i = i;
} } } }; } }}
Runnable b2 = new Runnable() { // Thread-2
public void run() {
synchronized (b) { // Thread-2 have resource2 but need resource1 also
synchronized (a) { Output:
System.out.println("In block 2");
} } } };
In block 1
new Thread(b1).start(); In block 2
new Thread(b2).start();
}
U23CA404 - Programming in Java 34
How to avoid deadlock?
• Deadlocks cannot be completely resolved. But we can avoid them by following
basic rules mentioned below:

1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this
is the main reason for a deadlock condition. It normally happens when you
give locks to multiple threads.
2. Avoid Unnecessary Locks: The locks should be given to the important
threads. Giving locks to the unnecessary threads that cause the deadlock
condition.
3. Using Thread Join: A deadlock usually happens when one thread is waiting
for the other to finish. In this case, we can use join with a maximum time
that a thread will take.

U23CA404 - Programming in Java 35


I/O Streams
• Java I/O (Input and Output) is used to process the input and produce
the output.
• 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.
• Java I/O revolves around two primary concepts: streams and
readers/writers

U23CA404 - Programming in Java 36


Stream
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
• In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
• Depending upon the data a stream holds, it can be classified into:
• Byte Stream
• Character Stream
U23CA404 - Programming in Java 37
Byte Stream
• Byte stream is used to read and write a single byte (8 bits) of data.
• All byte stream classes are derived from base abstract classes called
InputStream and OutputStream.

U23CA404 - Programming in Java 38


OutputStream Vs. InputStream
• OutputStream
• Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
• InputStream
• Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.

U23CA404 - Programming in Java 39


InputStream Class
• InputStream class is an abstract class. Method Description
• It is the superclass of all classes public abstract int read() throws
It reads the next byte of data from the
representing an input stream of bytes. IOException
input stream. It returns -1 at the end
of the file.
It returns an estimate of the number
public int available() throws
of bytes that can be read from the
IOException
current input stream.
public void close() throws It is used to close the current input
IOException stream.

U23CA404 - Programming in Java 40


Example Program
import java.io.FileInputStream;
import java.io.InputStream;
class Main {
public static void main(String args[]) {
byte[] array = new byte[100];
try {
InputStream input = new FileInputStream("input.txt");
System.out.println("Available bytes in the file: " + input.available());
// Read byte from the input stream
input.read(array);
System.out.println("Data read from the file: ");
// Convert byte array into string
String data = new String(array); Output:
System.out.println(data); Available bytes in the file: 39
// Close the input stream Data read from the file:
input.close(); This is a line of text inside the file
} catch (Exception e) {
e.getStackTrace();
}
}
} U23CA404 - Programming in Java 41
OutputStream Class
OutputStream class is an abstract class.
It is the superclass of all classes representing an
output stream of bytes.
An output stream accepts output bytes and sends
them to some sink.

Method Description

public void write(int) throws It is used to write a byte to the


IOException current output stream.
public void write(byte[])throws It is used to write an array of byte to
IOException the current output stream.
public void flush() throws
It flushes the current output stream.
IOException
public void close() throws It is used to close the current output
IOException stream.

U23CA404 - Programming in Java 42


Example Program
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
try {
OutputStream out = new FileOutputStream("output.txt");
// Converts the string into bytes
byte[] dataBytes = data.getBytes();
// Writes data to the output stream
out.write(dataBytes);
System.out.println("Data is written to the file.");
// Closes the output stream
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
U23CA404 - Programming in Java 43
Character Stream
• Character stream is used to read and write a single character of data.
• All the character stream classes are derived from base abstract classes
Reader and Writer.

U23CA404 - Programming in Java 44


Reader Class
The Reader class of the java.io package is an abstract superclass that represents a
stream of characters.
Since Reader is an abstract class, it is not useful by itself. However, its subclasses
can be used to read data.
Subclasses of Reader
In order to use the functionality of Reader, we can use its subclasses. Some of
them are:
•BufferedReader
•InputStreamReader
•FileReader
•StringReader

U23CA404 - Programming in Java 45


Methods of Reader
• The Reader class provides different methods that are implemented by its
subclasses. Here are some of the commonly used methods:
• ready() - checks if the reader is ready to be read
• read(char[] array) - reads the characters from the stream and stores in the
specified array
• read(char[] array, int start, int length) - reads the number of characters
equal to length from the stream and stores in the specified array starting from
the start
• mark() - marks the position in the stream up to which data has been read
• reset() - returns the control to the point in the stream where the mark is set
• skip() - discards the specified number of characters from the stream

U23CA404 - Programming in Java 46


import java.io.Reader;
import java.io.FileReader;
class Main {
Example Program
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a reader using the FileReader
Reader input = new FileReader("input.txt");
// Checks if reader is ready
System.out.println("Is there data in the stream? " + input.ready());
// Reads characters
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Closes the reader
input.close();
}
Output:
catch(Exception e) {
Is there data in the stream? true
e.getStackTrace();
Data in the stream:
}
This is a line of text inside the file.
}
} U23CA404 - Programming in Java 47
Writer Class
• The Writer class of the java.io package is an abstract superclass that
represents a stream of characters.
• Since Writer is an abstract class, it is not useful by itself. However, its
subclasses can be used to write data.
• Subclasses of Writer:
• In order to use the functionality of the Writer, we can use its subclasses.
Some of them are:
• BufferedWriter
• OutputStreamWriter
• FileWriter
• StringWriter

U23CA404 - Programming in Java 48


Methods of Writer class
• The Writer class provides different methods that are implemented by its
subclasses. Here are some of the methods:
• write(char[] array) - writes the characters from the specified array to
the output stream
• write(String data) - writes the specified string to the writer
• append(char c) - inserts the specified character to the current writer
• flush() - forces to write all the data present in the writer to the
corresponding destination
• close() - closes the writer

U23CA404 - Programming in Java 49


Example Program
import java.io.FileWriter;
import java.io.Writer;
public class Main {
public static void main(String args[]) {
String data = "This is the data in the output file";
try {
// Creates a Writer using FileWriter
Writer output = new FileWriter("output.txt");
// Writes string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
U23CA404 - Programming in Java 50
Reading console Input
• By default, to read from system console, we can use the Console class.
This class provides methods to access the character-based console, if any,
associated with the current Java process. To get access to Console, call
the method System.console().
• Console gives three ways to read the input:
• String readLine() – reads a single line of text from the console.
• char[] readPassword() – reads a password or encrypted text from the console with
echoing disabled
• Reader reader() – retrieves the Reader object associated with this console. This
reader is supposed to be used by sophisticated applications. For example, Scanner
object which utilizes the rich parsing/scanning functionality on top of the
underlying Reader.

U23CA404 - Programming in Java 51


Reading Input with readLine() Reading Input with readPassword() Read Input with reader()

Console console =
System.console();
Console console =
Console console = if(console == null) {
System.console();
System.console(); System.out.println("Console is not
if(console == null) {
if(console == null) { available to current JVM process");
System.out.println("Console is not
System.out.println("Console is not return; }
available to current JVM process");
available to current JVM process"); Reader consoleReader =
return; }
return; } console.reader();
char[] password =
String userName = Scanner scanner = new
console.readPassword("Enter the
console.readLine("Enter the Scanner(consoleReader);
password: ");
username: "); System.out.println("Enter age:");
System.out.println("Entered
System.out.println("Entered int age = scanner.nextInt();
password: " + new
username: " + userName); System.out.println("Entered age: "
String(password));
+ age);
scanner.close();

Enter the password: //input will not Enter age:


Enter the username: lokesh
visible in the console 12
Entered username: lokesh
EnteredU23CA404
password: passphrase
- Programming in Java
Entered age: 12 52
Writing Console output
• The easiest way to write the output data to console is System.out.println() statements. Still, we can use
printf() methods to write formatted text to console
1. Writing with System.out.println
• System.out.println("Hello, world!");
Program output
• Hello, world!
2. Writing with printf()
• The printf(String format, Object... args) method takes an output string and multiple parameters which
are substituted in the given string to produce the formatted output content. This formatted output is
written in the console.
String name = "Lokesh";
int age = 38;
console.printf("My name is %s and my age is %d", name, age);
• Program output
My name is Lokesh and my age is 38

U23CA404 - Programming in Java 53


File Handling
• The File class of the java.io package is used to perform various
operations on files and directories.
• A file is a named location that can be used to store related information.
For example, main.java is a Java file that contains information about the
Java program.
• A directory is a collection of files and subdirectories. A directory inside a
directory is known as subdirectory.
• To create an object of File, we need to import the java.io.File package
first. Once we import the package, here is how we can create objects of
file.
// creates an object of File using the path
File file = new File(String pathName);

U23CA404 - Programming in Java 54


File operation methods
Operation Method Package

To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

U23CA404 - Programming in Java 55


Creating a new File
• To create a new file, we can use the createNewFile() method. It returns
• true if a new file is created.
• false if the file already exists in the specified location.
import java.io.File;
class Main {
public static void main(String[] args) {
File file = new File("newFile.txt"); // create a file object for the current location
try {
boolean value = file.createNewFile(); // trying to create a file based on the object
if (value) {
System.out.println("The new file is created.");
If newFile.txt doesn't exist in the current location, the file is
}
created and this message is shown.
else {
System.out.println("The file already exists."); The new file is created.
}
However, if newFile.txt already exists, we will see this message.
}
catch(Exception e) { The file already exists.
e.getStackTrace();
} }}
U23CA404 - Programming in Java 56
Reading a file
• To read data from the file, we can use subclasses of either InputStream
or Reader.
// importing the FileReader class
import java.io.FileReader;
class Main {
public static void main(String[] args) {
char[] array = new char[100];
try {
FileReader input = new FileReader("input.txt"); // Creates a reader using the FileReader
input.read(array); // Reads characters
System.out.println("Data in the file:");
System.out.println(array);
input.close(); // Closes the reader
}
catch(Exception e) { Output:
e.getStackTrace(); Data in the file:
} This is a line of text inside the file.
}
} U23CA404 - Programming in Java 57
Writing to a file
• To write data to the file, we can use subclasses of either OutputStream or
Writer.
import java.io.FileWriter;
class Main {
public static void main(String args[]) {
String data = "This is the data in the output file";
try {
FileWriter output = new FileWriter("output.txt"); // Creates a Writer using FileWriter
output.write(data); // Writes string to the file
System.out.println("Data is written to the file.");
output.close(); // Closes the writer
}
catch (Exception e) {
e.getStackTrace();
Output:
}
Data is written to the file.
}
}

U23CA404 - Programming in Java 58


Deleting a file
• We can use the delete() method of the File class to delete the specified file or
directory. It returns
• true if the file is deleted.
• false if the file does not exist.
import java.io.File;
class Main {
public static void main(String[] args) {
// creates a file object
File file = new File("file.txt");
// deletes the file
boolean value = file.delete();
if(value) {
System.out.println("The File is deleted.");
} Output:
else { The File is deleted.
System.out.println("The File is not deleted.");
}
}
} U23CA404 - Programming in Java 59

You might also like