Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

UNIT V

Multithreading
A thread is similar to a program that has single flow of control. It has a beginning, a body and an end and
execute commands sequentially. All the main programs in our earlier examples can be called single
threaded programs. Every program will have at least one thread as shown below.
class Chakry  Begin
{
........
........
 Single Threaded body of
........ execution
....
..  End
}
A program that contains multiple flows of control is known as multithreaded program. The following diagram shows
a java program with four threads, one main thread and three others.
Main Thread

Main Thread Program

start() start() start()

switching switching
Thread A Thread B Thread C

What is Thread?
 A thread is a single sequential flow of control within a program.
 A thread is a lightweight sub-process, the smallest unit of processing.
 Multithreading in Java is a process of executing multiple threads simultaneously.
 Multithreading 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.
 It differs from a “process” in that a process is a program executing in its own address space whereas
a thread is a single stream of execution within a process.
 Java Multithreading is mostly used in games, animation, etc.

What is Multithreading in Java?


MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum
utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is
also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate
separate memory area, hence they save memory. Also, context switching between threads takes less time

Advantages of Java 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.

The Java Thread Model (Explain Java Thread Model)


In java, threads are implemented in the form of objects that contain a method called run() method. The
run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only
method in which the threads behavior can be implemented. The run() appear as follows.
public void run()
{
…………….
……………. // Statements for implementing thread
}
1
UNIT V

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating
the thread and initiating it with the help of another thread method called “start()”. Some of the methods
which are available in Thread class as shown below:
S.N Modifier Method Description
o and Type

1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static currentThread( It returns a reference to the currently executing thread object.


Thread )

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and all of its subgroups.

17) Thread.State getState() It is used to return the state of the thread.

18) void notify() It is used to give the notification for only one thread which is
waiting for a particular object.

19) void notifyAll() It is used to give the notification to all waiting threads of a
particular object.

LIFE CYCLE OF A THREAD


During the life time of a thread, there are many states it can enter. They include
1.New born state
2.Runnable state
3.Running state
4.Blocked state
5.Dead state

2
UNIT V

A thread is always in one of these 5 states. It can move from one state to another in many ways as
shown below.
New Thread New Born

stop( )
start( )

stop( )
Active Thread Running Runnable Killed Thread
Dead
yield()

sleep( ) resume( )
suspend( ) notify( ) stop( )
wait( )
Idle Thread Blocked
( Not
( Not Run)
Runnable)
( Not Run)
1. New born state: In this phase, the thread is created using class "Thread class". It remains in this state till
the program starts the thread. It is also known as born thread.
2. Runnable state: In this state, the instance of the thread is invoked with a start() method. The thread
control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the
thread.
3. Running state: When the thread starts executing, then the state is changed to "running" state. The
scheduler selects one thread from the thread pool, and it starts executing in the application.
4. Waiting(Blocked) state: This is the state when a thread has to wait. As there multiple threads are
running in the application, there is a need for synchronization between threads. Hence, one thread has to
wait, till the other thread gets executed. Therefore, this state is referred as waiting state.
5. Dead state: This is the state when the thread is terminated. The thread is in running state and as soon as
it completed processing it is in "dead state".
The program uses the following methods yield( ), sleep( ) and stop( ).
Program:
class A extends Thread
{
public void run ( )
{
for(int i=1; i<=20; i++)
{
if (i==3)
yield ( );
System.out.println(“From thread A: i= “+i);
}
}
}
class B extends Thread
{
public void run ( )
{
for (int j=1;j<=20;j++)
{
if (j==10)
stop ( );
System.out.println(“From thread B: j=”+j);
}
3
UNIT V

}
}
class C extends Thread
{
public void run ( )
{
for (int k=1;k<=20;k++)
{
try
{
sleep(1000);
}
catch (Exception e) { }
System.out.println(“From thread C: k=”+k);
}
}
}
class ThreadMethods
{
public static void main(String args[ ])
{
A p=new A( );
B q=new B( );
C r=new C( );
p.start( );
q.start( );
r.start( );
}
}
Creating threads
A new thread can be created in two ways.
1. By creating a thread class: Define a class that extends thread class and override its run() method with
the code required by the thread.
2. By converting a class to a thread(Using Runnable interface): Define a class that implements
Runnable interface. The Runnable interface has only one method, run( ), i.e., to be defined in the method
with the code to be executed by the thread.
I. EXTENDING THE THREAD CLASS
We can make our class runnable as thread by extending the class java.lang. Thread. This allows us to
access all the thread methods directly. It includes the following steps.
1. Declare the class as extending the Thread class.
2. Implement the run() method .
3. Create a thread object and call the start().
1. Declaring the thread class:
The thread can be extended as follows
class MyThread extends Thread
{
……….…….
……………..
} //Now we have a new type of thread MyThread.
2. Implementing the run ( ) method
The run ( ) method has been inherited by the class ‘MyThread’. We have to override this method in order to
implement the code to be executed by our thread. The basic implementation of run( ) is as follows
public void run()
{
…………..
………….. // Thread code here
4
UNIT V

}
When we start the new thread, java calls the threads run( ) method.
3. Starting New Thread:To create and run an instance of our thread class we must write the following.
MyThread aThread=new MyThread ( ); //Creation
aThread.start( ); //invokes run( ) method
The thread is also started by using the following statement.
new MyThread ( ).start( );
STOPPING AND BLOCKING A THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do by calling its stop( ) method.
aThread.stop( );
Here aThread is a thread object.
This statement causes the thread to move to the Dead state. A thread will also move to the dead state
automatically when it reaches the end of its method. The stop( ) method may be used when the thread is to
be stopped before its completion.
Blocking a thread
A thread can also be temporarily suspended (or) blocked from entering into the runnable and running state
by using the following thread methods.
sleep ( ) // blocked for a specified time.
suspend ( ) // blocked until further orders.
wait ( ) // blocked until certain conditions occur.
These methods cause the thread to go into the blocked state. The thread will return to the runnable
state when the specified time is elapsed in the case of sleep ( ), the resume ( ) method is invoked in the
case of suspend ( ), and the notify ( ) method is called in the case of wait( ) method.

2) Java Thread Example by implementing Runnable interface


The second method to create the threads is by using the Runnable interface. The Runnable
interface declares the run( ) method that is required for implementing threads in our programs. To do this,
we must perform the following steps.
(1) Declare the class as implementing the Runnable interface
(2) Implementing the run( ) method
(3) Create a thread by defining an object that is instantiated from the runnable class as the target of the
thread. Calls the thread’s start( ) method to run the thread.
1. class Multi3 implements Runnable{  
2. public void run(){  
3. System.out.println("thread is running...");  
4. }  
5.    Output:thread is running...
6. public static void main(String args[]){  
7. Multi3 m1=new Multi3();  
8. Thread t1 =new Thread(m1);  
9. t1.start();  
10.  }  
11. }  
NOTE
If you are not extending the Thread class,your class object would not be treated as a thread object.
So you need to explicitely create Thread class object.
We are passing the object of your class that implements Runnable so that your class run() method
may execute.
Sleep() method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:

5
UNIT V

 public static void sleep(long miliseconds)throws InterruptedException


 public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
1. class TestSleepMethod1 extends Thread{  
2.  public void run(){  
3.   for(int i=1;i<5;i++){  
4.     try{
5. Thread.sleep(500);
6. }
7. catch(InterruptedException e){System.out.println(e);}  
8.     System.out.println(i);  
9.   }  
10.  }  
11.  public static void main(String args[]){  
12.   TestSleepMethod1 t1=new TestSleepMethod1();  
13.   TestSleepMethod1 t2=new TestSleepMethod1();  
14.   t1.start();  
15.   t2.start();  
16.  }  
17. }  

NOTE
Can we start a thread twice (2m)
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is
thrown. In such case, thread will run once but for second time, it will throw exception.
What if we call run() method directly instead start() method(2m)
 Each thread starts in a separate call stack.
 Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
The join() method
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
1. class TestJoinMethod1 extends Thread{  
2.  public void run(){  
3.   for(int i=1;i<=5;i++){  
4.    try{  
5.     Thread.sleep(500);  
6.    }catch(Exception e){System.out.println(e);}  
7.   System.out.println(i);  
8.   }   }  
9. public static void main(String args[]){  
10.  TestJoinMethod1 t1=new TestJoinMethod1();  
11.  TestJoinMethod1 t2=new TestJoinMethod1();  
12.  TestJoinMethod1 t3=new TestJoinMethod1();  
6
UNIT V

13.  t1.start();  
14.  try{  
15.   t1.join();  
16.  }catch(Exception e){System.out.println(e);}  
17.   t2.start();  
18.  t3.start();  
19.  }  }  

Naming Thread and Current Thread


The Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread
1. class TestMultiNaming1 extends Thread{  
2.   public void run(){  
3.    System.out.println("running...");  
4.   }  
5.  public static void main(String args[]){  
6.   TestMultiNaming1 t1=new TestMultiNaming1();  
7.   TestMultiNaming1 t2=new TestMultiNaming1();  
8.   System.out.println("Name of t1:"+t1.getName());  
9.   System.out.println("Name of t2:"+t2.getName());  
10.    t1.start();  
11.   t2.start();  
12.    t1.setName("NECN");  
13.   System.out.println("After changing name of t1:"+t1.getName());  
14.  }  
15. }  

Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular 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.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. 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.

Example of priority of a Thread:


1. class TestMultiPriority1 extends Thread{  
2.  public void run(){  
3.    System.out.println("running thread name is:"+Thread.currentThread().getName());  
4.    System.out.println("running thread priority is:"+Thread.currentThread().getPriority());  
5.     }  

7
UNIT V

6.  public static void main(String args[]){  
7.   TestMultiPriority1 m1=new TestMultiPriority1();  
8.   TestMultiPriority1 m2=new TestMultiPriority1();  
9.   m1.setPriority(Thread.MIN_PRIORITY);  
10.   m2.setPriority(Thread.MAX_PRIORITY);  
11.   m1.start();  
12.   m2.start();     
13.  }  }     

Deadlock in java
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.
Synchronization in Java
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.
Why use Synchronization (2M)
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
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1.1 Synchronized method.
1.2 Synchronized block.
1.3 static synchronization.
2. Cooperation (Inter-thread communication in java)

1. 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.

Understanding the problem without Synchronization (Generating 5th Table 10th Table )
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1. class Table{  
2. void printTable(int n){//method not synchronized  
3.    for(int i=1;i<=5;i++){  
4.      System.out.println(n*i);  
5.      try{  

8
UNIT V

6.       Thread.sleep(1000);  
7.      }catch(Exception e){System.out.println(e);}  
8.    }   }  }  
9.   class MyThread1 extends Thread{  
10. Table t;  
11. MyThread1(Table t){  
12. this.t=t;  
13. }  
14. public void run(){  
15. t.printTable(5);  
16. }  }  
17. class MyThread2 extends Thread{  
18. Table t;  
19. MyThread2(Table t){  
20. this.t=t;  
21. }  
Output: 5
22. public void run(){   100
23. t.printTable(100);   10
24. }  }   200
25.    15
26. class TestSynchronization1{   300
27. public static void main(String args[]){   20
400
28. Table obj = new Table();//only one object  
25
29. MyThread1 t1=new MyThread1(obj);  
500
30. MyThread2 t2=new MyThread2(obj);  
31. t1.start();  
32. t2.start();  
33. }  }  
From the above output that both the 5th Table and 100th Table values are jumbles and messed with each
other, since “void printTable(int n)” is not synchronized .
Generating 5th Table 10th Table using synchronized  Method
1. class Table{  
2.  synchronized void printTable(int n){//synchronized method  
3.    for(int i=1;i<=5;i++){  
4.      System.out.println(n*i);  
5.      try{  
6.       Thread.sleep(400);  
7.      }catch(Exception e){System.out.println(e);}  
8.    }     }  }  
9.   class MyThread1 extends Thread{   Output: 5
10. Table t;   10
11. MyThread1(Table t){   15
12. this.t=t;   20
13. }   25
100
14. public void run(){  
200
15. t.printTable(5);   300
16. }   }   400
17. class MyThread2 extends Thread{   500
18. Table t;  
9
UNIT V

19. MyThread2(Table t){  
20. this.t=t;  
21. }  
22. public void run(){  
23. t.printTable(100);  
24. }  }  
25.   public class TestSynchronization2{  
26. public static void main(String args[]){  
27. Table obj = new Table();//only one object  
28. MyThread1 t1=new MyThread1(obj);  
29. MyThread2 t2=new MyThread2(obj);  
30. t1.start();  
31. t2.start();  
32. }  }  
Now, the output is clear and printed one after another (5th Table then 100th Table)
2. Synchronized Block in Java
1. Synchronized block can be used to perform synchronization on any specific resource of the method.
2. Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
3. If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1. synchronized (object reference expression) {   
2.   //code block   
3. }  
Example of synchronized block Let's see the simple example of synchronized block.
1. class Table{  
2.  void printTable(int n){   Output:5
3.    synchronized(this){//synchronized block   10
4.      for(int i=1;i<=5;i++){   15
5.       System.out.println(n*i);   20
6.       try{   25
100
7.        Thread.sleep(400);  
200
8.       }catch(Exception e){System.out.println(e);}  
300
9.      }   400
10.    }   500
11.  }//end of the method  
12. }  
13. class MyThread1 extends Thread{  
14. Table t;  
15. MyThread1(Table t){  
16. this.t=t;  
17. }  
18. public void run(){  
19. t.printTable(5);  

10
UNIT V

20. }  }  
21. class MyThread2 extends Thread{  
22. Table t;  
23. MyThread2(Table t){  
24. this.t=t;  
25. }  
26. public void run(){  
27. t.printTable(100);  
28. }  }  
29.
30. public class TestSynchronizedBlock1{  
31. public static void main(String args[]){  
32. Table obj = new Table();//only one object  
33. MyThread1 t1=new MyThread1(obj);  
34. MyThread2 t2=new MyThread2(obj);  
35. t1.start();  
36. t2.start();  
37. }  }  

Inter-thread communication in Java


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.
Example for Inter-thread communication
Producer-Consumer Problem
The producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a
multi-thread synchronization problem. The problem describes two threads/processes, the producer and the
consumer, which share a common, fixed-size buffer used as a queue.
 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a
time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t
try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer
removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same
way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data
into the buffer, it wakes up the sleeping consumer.
It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
1) wait() method
 Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.

11
UNIT V

 The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.
wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
completed.

Example of inter thread communication in java (as withdraw– Consumer; Deposit- Producer)
Let's see the simple example of inter thread communication.
1. class Customer{  
2. int amount=10000;  
3. synchronized void withdraw(int amount){  
4. System.out.println("going to withdraw...");  
5. if(this.amount<amount){  
6. System.out.println("Less balance; waiting for deposit...");  
7. try{wait();}catch(Exception e){}  
8. }  
9. this.amount-=amount;  
10. System.out.println("withdraw completed...");  
11. }  
12. synchronized void deposit(int amount){  
13. System.out.println("going to deposit...");  
14. this.amount+=amount;  
15. System.out.println("deposit completed... ");  
12
UNIT V

16. notify();  
17. }  
18. }   
19. class Test{  
20. public static void main(String args[]){  
21. final Customer c=new Customer();  
22. new Thread(){   This is called “anonymous calling” ,
23. public void run(){c.withdraw(15000);}   i.e without creating an object.
24. }.start();  
25.
26. new Thread(){  
27. public void run(){c.deposit(10000);}  
28. }.start();  
29. }}  
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

13
UNIT V

StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string.
Constructors of StringTokenizer class
Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.

StringTokenizer(String str, String delim, creates StringTokenizer with specified string, delimeter and
boolean returnValue) returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters
serve to separate tokens.

The 6 useful methods of StringTokenizer class are as follows:

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

1. import java.util.*;  
2.  public class Test {  
3.    public static void main(String[] args) {  
4.        StringTokenizer st = new StringTokenizer("my,name,is,SURESH BABU");   
5.       // printing next token  
6.       System.out.println("Next token is : " + st.nextToken(","));  
7.    }      }  
Date and Time
The following packages contains classes for representing date and time.
 java.time,
 java.util,
 java.sql and
 java.text
Java has introduced a new Date and Time API since Java 8.
java.util.Date
 The java.util.Date class represents date and time in java.
 It provides constructors and methods to deal with date and time in java.
 It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

14
UNIT V

 After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors
No Constructor Description
.

1) Date() Creates a date object representing current date and time.

2) Date(long milliseconds) Creates a date object for the given milliseconds since January 1, 1970,
00:00:00 GMT.

java.util.Date Methods
No. Method Description

1) boolean after(Date date) tests if current date is after the given date.

2) boolean before(Date date) tests if current date is before the given date.

3) Object clone() returns the clone object of current date.

4) int compareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for equality.

6) static Date from(Instant instant) returns an instance of Date object from Instant date.

7) long getTime() returns the time represented by this date object.

8) int hashCode() returns the hash code value for this date object.

9) void setTime(long time) changes the current date and time to given time.

java.util.Date Example
1. public class UtilDateExample1{
2. public static void main(String args[]){
3. java.util.Date date=new java.util.Date(); Output
4. System.out.println(date); Tue Feb 16 10:12:02 IST 2021
Tue Feb 16 10:12:02 IST 2021
5. long millis=System.currentTimeMillis();
6. java.util.Date date1=new java.util.Date(millis);
7. System.out.println(date);
8. }}

java.sql.Date
 The java.sql.Date class represents only date in java. It inherits java.util.Date class.
 The java.sql.Date instance is widely used in JDBC because it represents the date that can be stored
in database.
java.sql.Date Constructor
No Constructor Description
.

15
UNIT V

1) Date(long Creates a sql date object for the given milliseconds since January 1, 1970,
milliseconds) 00:00:00 GMT.
java.sql.Date Methods
No. Method Description

1) void setTime(long time) changes the current sql date to given time.

3) LocalDate toLocalDate() converts current sql date into LocalDate object.

4) String toString() converts this sql date object to a string.

5) static Date valueOf(LocalDate date) returns sql date object for the given LocalDate.

6) static Date valueOf(String date) returns sql date object for the given String.

java.sql.Date Example: get current date


Let's see the example to print date in java using java.sql.Date class.
1. public class SQLDateExample {  
2.     public static void main(String[] args) {  
3.         long millis=System.currentTimeMillis();  
Output:
4.         java.sql.Date date=new java.sql.Date(millis);   2021-02-16
5.         System.out.println(date);  
6.     }  }  

Calendar Class
Java Calendar class is an abstract class that provides methods for converting date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and
implements the Comparable interface.
Example
1. import java.util.Calendar;  
2. public class CalendarExample1 {  
3.    public static void main(String[] args) {  
4.    Calendar calendar = Calendar.getInstance();  
5.    System.out.println("The current date is : " + calendar.getTime());  
6.    calendar.add(Calendar.DATE, -15);  
7.    System.out.println("15 days ago: " + calendar.getTime());   OUTPUT
The current date is : Tue Feb 16 10:17:39 IST 2021
8.    calendar.add(Calendar.MONTH, 4);   15 days ago: Mon Feb 01 10:17:39 IST 2021
9.    System.out.println("4 months later: " + calendar.getTime());   4 months later: Tue Jun 01 10:17:39 IST 2021
10.    calendar.add(Calendar.YEAR, 2);   2 years later: Thu Jun 01 10:17:39 IST 202

11.    System.out.println("2 years later: " + calendar.getTime());  
12.    } 
13.  }  

Some Important Methods

No Method Description

1. public void add(int field, int amount) Adds the specified (signed) amount of time to the
given calendar field.

16
UNIT V

2. public boolean after (Object when) The method Returns true if the time represented by
this Calendar is after the time represented by when
Object.

3. public boolean before(Object when) The method Returns true if the time represented by
this Calendar is before the time represented by when
Object.

4. public final void clear(int field) Set the given calendar field value and the time value
of this Calendar undefined.

5. public Object clone() Clone method provides the copy of the current object.

6. public boolean equals(Object object) The equals() method compares two objects for
equality and Returns true if they are equal.

7. public static Calendar getInstance() This method is used with calendar object to get the
instance of calendar according to current time zone
set by java runtime environment

8. public final Date getTime() This method gets the time value of calendar object
and Returns date.

9. public void set(int field, int value) Sets the specified calendar field by the specified
value.

10. public final void setTime(Date date) Sets the Time of current calendar object. A Date
object id passed as the parameter.

Random class
Random class is used to generate pseudo-random numbers in java.
An instance of this class is thread-safe. This class provides various method calls to generate different
random data types such as float, double, int.
Constructors:
 Random(): Creates a new random number generator
 Random(long seed): Creates a new random number generator using a single long seed

1. // Java program to demonstrate


2. // method calls of Random class OutPut
3. import java.util.Random; 4
4. public class Test
true
5. {
0.19674934340402916
6. public static void main(String[] args)
0.7372021
7. {
1.4877581394085997
8. Random random = new Random();
9. System.out.println(random.nextInt(10)); [-44 75 68 89 81 -72 -1 -66 -64 117 ]

10. System.out.println(random.nextBoolean()); 158739962004803677

11. System.out.println(random.nextDouble()); -1344764816

17
UNIT V

12. System.out.println(random.nextFloat());
13. System.out.println(random.nextGaussian());
14. byte[] bytes = new byte[10];
15. random.nextBytes(bytes);
16. System.out.printf("[");
17. for(int i = 0; i< bytes.length; i++)
18. {
19. System.out.printf("%d ", bytes[i]);
20. }
21. System.out.printf("]\n");
22. System.out.println(random.nextLong());
23. System.out.println(random.nextInt());
24. }}

Formatter class

The java.util.Formatter class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.
Following are the important points about Formatter –
Important Format Specifiers
Format Example & Output
Description
Specifier
Space When creating columns of numbers, it is formatter.format("% d", -111);
sometimes very useful to print a space before a Output:
positive number so that positive and negative -111
number get aligned. To do this, space format
specifier can be used.
+ Sign This adds the + sign before positive numeric Formatter().format("%+d", 111);
value, and has no effect on negative numeric Output:
value. +111

( specifier Formatter().format("%(d", -111);


This specifier puts the negative numeric values Formatter().format("%(d", 111);
inside the parentheses, and has no effect on the Output:
positive numeric values. (111)
111

Comma, Formatter().format("%, d",


Specifier 1000000);
displaying large numbers, it is often useful to
Output:
add grouping separators by comma (, ).
1, 000, 000

Left For Left Justification Formatter().format("|%-20.4f|",


Justification 1234.1234);
Output:
| 1234.1234|
|1234.1234 |

18
UNIT V

The %n formatter.format("NECN %n CSE


format %n NELLORE");
Output:
New Line NECN
CSE
NELLORE

The %% formatter.format("10 %% 4 = 2");


It is simply an escape sequence that inserts a
format Output
character into the output. The %% inserts a %
10 % 4 = 2
sign.

The %e %E formatter.format("%e", 123.1234);


format Output
The %e or %E format specifier is is used to
represent the Scientific Notation of a value
1.231234e+02

Precision A precision specifier can be applied to the %f,


%e, %g, and %s format specifiers

import java.util.Formatter;
  public class GFG {
    public static void main(String args[])
    {
          // Create the Formatter instance
        Formatter formatter = new Formatter();
        formatter = new Formatter();
        formatter.format("%16.2e", 123.1234567);
        System.out.println("Scientific notation to 2 places: "   + formatter);
  
        // Format 4 decimal places.
        formatter = new Formatter();
        formatter.format("%.4f", 123.1234567);
        System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter);
  
        // Format 4 places.
        // The %g format specifier causes Formatter
        // to use either %f or %e, whichever is shorter
        formatter = new Formatter();
        formatter.format("%.4g", 123.1234567);
        System.out.println("Scientific or Decimal floating-point "+ "notation to 4 places: " +
formatter);
  
        // Display at most 15 characters in a string.
        formatter = new Formatter();
        formatter.format("%.15s", "12345678901234567890");

19
UNIT V

        System.out.println("String notation to 15 places: " + formatter);


          // Format into 10 digit
        formatter = new Formatter();
        formatter.format("%010d", 88);
        System.out.println("value in 10 digits: "+formatter);
    } }

Output:
Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
Scanner Class
1. The scanner class is a class in java.util, which allows the user to read values of various types.
2. A scanner object can read user input entered on the console or from a file.
3. A scanner breaks its input into separate tokens and returns them at a time.
4. The scanner provides methods to convert the tokens into values of different types.
5. A Scanner is not safe for multithreaded use without external synchronization.
Syntax:
Scanner s=new Scanner(System.in);
int i = s.nextInt( );
We can create scanners in two ways
1. To read from the console
Scanner s = new Scanner(System.in);
2. To read from a file
Scanner s = new Scanner(new FileStream(“filename.txt”));
Constructors:
Scanner(File source)
 Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(String source)
  Constructs a new Scanner that produces values scanned from the specified string.
Scanner Methods :
Scanner Method Description
nextInt( ) Reads and converts next token to a integer value
nextLong( ) Reads and converts next token to a long value
nextDouble( ) Reads and converts next token to a double value
nextString( ) Reads a String
(or) next()
nextBoolean( ) Reads and converts next token to a boolean value

Java-Stream Classes

20
UNIT V

In Java, a stream is a path along which the data flows. Every stream has a source and a destination. We can
build a complex file processing sequence using a series of simple stream operations.

Class Hierarchy of Stream Class

Types of Streams

The java.io package contains a large number of stream classes that provide capabilities for processing all
types of data. These classes may be categorized into two groups based on the data type on which they
operate.

 Byte stream classes


 Character stream classes
Byte Stream Classes
 Byte stream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing bytes.
 Java provides two kinds of byte stream classes: 
o input stream classes and 
o output stream classes.
21
UNIT V

Input Stream Classes


Input stream classes that are used to read bytes include a super class known as “Inputstream” and a number
of subclasses for supporting various input-related functions. The super class InputStream is an abstract
class, and, therefore, we cannot create instances of this class. Rather, we must use the subclasses that
inherit from this class.

Output Stream Classes


Output stream classes are derived from the base class “Outputstream” like InputStream, the OutputStream
is an abstract class and therefore we cannot instantiate it. The several subclasses of the OutputStream can
be used for performing the output operations.

These two abstract classes have several concrete classes that


handle various devices such as disk files, network
connection etc.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method


These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data

Example Input/Output Streams Reading and writing Files


Following Java program reads data from a particular file using FileInputStream and writes it to another,
using FileOutputStream.
import java.io.File;

22
UNIT V

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOStreamsExample {
   public static void main(String args[]) throws IOException {
      //Creating FileInputStream object
      File file = new File("D:/myFile.txt");
      FileInputStream fis = new FileInputStream(file);
      byte bytes[] = new byte[(int) file.length()];
      //Reading data from the file
      fis.read(bytes);
      //Writing data to another file
      File out = new File("D:/CopyOfmyFile.txt");
      FileOutputStream outputStream = new FileOutputStream(out);
      //Writing data to the file
      outputStream.write(bytes);
      outputStream.flush();
      System.out.println("Data successfully written in the specified file");
   }
}
Output
Data successfully written in the specified file

Character Stream Classes
Character streams can be used to read and write 16-bit Unicode characters. Like byte streams, there are two
kinds of character stream classes, namely, reader stream classes and writer stream classes.

Reader Stream Classes


Reader stream classes that are used to read characters include a super class known as Reader and a number
of subclasses for supporting various input-related functions. Reader stream classes are functionally very
similar to the input stream classes, except input streams use bytes as their fundamental unit of information,
while reader streams use characters. The Reader class contains methods that are identical to those available
in the InputStream class, except Reader is designed to handle characters. Therefore, reader classes can
perform all the functions implemented by the input stream classes.

Writer Stream Classes


Like output stream classes, the writer stream classes are designed to perform all output operations on files.
Only difference is that while output stream classes are designed to write bytes, the writer stream are
designed to write character. The Writer class is an abstract class which acts as a base class for all the
other writer stream classes. This base class provides support for all output operations by defining methods
that are identical to those in Outputstream class.

23
UNIT V

These two abstract classes have several concrete classes that handle unicode character.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Example Reader/Writer Streams (Reading and writing Files)


Following Java program reads data from a particular file using FileReader and writes it to another, using
FileWriter.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOStreamsExample {
   public static void main(String args[]) throws IOException {
      //Creating FileReader object
      File file = new File("D:/myFile.txt");
      FileReader reader = new FileReader(file);
      char chars[] = new char[(int) file.length()];
      //Reading data from the file
      reader.read(chars);
      //Writing data to another file
      File out = new File("D:/CopyOfmyFile.txt");
      FileWriter writer = new FileWriter(out);
      //Writing data to the file
      writer.write(chars);
      writer.flush();
      System.out.println("Data successfully written in the specified file");
   }
24
UNIT V

}
Output
Data successfully written in the specified file

Reading console Input and Writing Console Output

In Java, there are three different ways for reading input from the user in the command line environment
(console).
1.Using Buffered Reader Class
 This is the Java classical method to take input, Introduced in JDK1.0.
 This method is used by wrapping the System.in (standard input stream) in an InputStreamReader
which is wrapped in a BufferedReader, we can read input from the user in the command line.
Advantages
 The input is buffered for efficient reading.
Drawback:
 The wrapping code is hard to remember.
Program:

// Java program to demonstrate BufferedReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test 
{
    public static void main(String[] args) throws IOException 
    {
        //Enter data using BufferReader
        BufferedReader reader = 
                   new BufferedReader(new InputStreamReader(System.in));
          // Reading data using readLine
        String name = reader.readLine();
  
        // Printing the read line
        System.out.println(name);        
    }
}

Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble().


2. Using Scanner Class
 This is probably the most preferred method to take input.
 The main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user in the command line.
Advantages:

 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
 Regular expressions can be used to find tokens.
25
UNIT V

Drawback:
 The reading methods are not synchronized

// Java program to demonstrate working of Scanner in Java


import java.util.Scanner;
  
class GetInputFromUser
{
    public static void main(String args[])
    {
        // Using Scanner for Getting Input from User
        Scanner in = new Scanner(System.in);
  
        String s = in.nextLine();
        System.out.println("You entered string "+s);
  
        int a = in.nextInt();
        System.out.println("You entered integer "+a);
  
        float b = in.nextFloat();
        System.out.println("You entered float "+b);
    }
}

3. Using Console Class


It has been becoming a preferred way for reading user’s input from the command line. In addition, it can
be used for reading password-like input without echoing the characters entered by the user; the format
string syntax can also be used (like System.out.printf()).
Advantages:
 Reading password without echoing the entered characters.
 Reading methods are synchronized.
 Format string syntax can be used.
Drawback:
 Does not work in non-interactive environment (such as in an IDE).

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. Java program to read
console input with readLine()

26
UNIT V

Console readLine() method example


Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
String userName = console.readLine("Enter the username: ");
System.out.println("Entered username: " + userName);

Java program to read console input with readPassword()


Console readPassword() method example
Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
char[] password = console.readPassword("Enter the password: ");
System.out.println("Entered password: " + new String(password));

reader()

Console reader() method example


Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
Reader consoleReader = console.reader();
Scanner scanner = new Scanner(consoleReader);
System.out.println("Enter age:");
int age = scanner.nextInt();
System.out.println("Entered age: " + age);
scanner.close();

Writing Console Output in Java

 print() and println()


 Both print() and println() methods are used to direct the output to the console. These methods are
defined in the PrintStream class and are widely used.

 The basic differences between print() and println() methods is that print() method displays the
string in the same line whereas println() method outputs a newline character after its execution.

 The write() method


Alternatively, you can make use of the write() method for directing the output of your program to the
console. The easiest syntax of the write() method is:

void write(int b);

27
UNIT V

Where b is an integer of low order eight bits.

 
1. class writeEg
2. {
3.             public static void main(String args[])
4.             {
5.                         int a, b;
6.                         a = 'Q';
7.                         b = 65;
8.                       System.out.write(a);
9.                       System.out.write('\n');
10.                       System.out.write(b);
11.                       System.out.write('\n');
12.             }
13. }

Java File Class

The File class is an abstract representation of file and directory pathname.


Constructors
Constructor Description

File(File parent, String child) It creates a new File instance from a parent abstract pathname and a
child pathname string.

File(String pathname) It creates a new File instance by converting the given pathname string
into an abstract pathname.

File(String parent, String It creates a new File instance from a parent pathname string and a child
child) pathname string.

File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
Useful Methods
Method Description

createNewFile() It atomically creates a new, empty file named by this abstract pathname
if and only if a file with this name does not yet exist.

canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]

canExecute() It tests whether the application can execute the file denoted by this
abstract pathname.

canRead() It tests whether the application can read the file denoted by this abstract
pathname.

isAbsolute() It tests whether this abstract pathname is absolute.

isDirectory() It tests whether the file denoted by this abstract pathname is a directory.

isFile() It tests whether the file denoted by this abstract pathname is a normal
file.

28
UNIT V

getName() It returns the name of the file or directory denoted by this abstract
pathname.

getParent() It returns the pathname string of this abstract pathname's parent, or null
if this pathname does not name a parent directory.

toPath() It returns a java.nio.file.Path object constructed from the this abstract


path.

toURI() It constructs a file: URI that represents this abstract pathname.

listFiles() It returns an array of abstract pathnames denoting the files in the


directory denoted by this abstract pathname

getFreeSpace() It returns the number of unallocated bytes in the partition named by this
abstract path name.

list(FilenameFilter filter) It returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname that satisfy the specified
filter.

mkdir() It creates the directory named by this abstract pathname.

Java File Example 1: New File Creation

1. import java.io.*;  
2. public class FileDemo {  
3.     public static void main(String[] args) {  
4.   
5.         try {  
6.             File file = new File("javaFile123.txt");  
7.             if (file.createNewFile()) {  
8.                 System.out.println("New File is created!");  
9.             } else {  
10.                 System.out.println("File already exists.");  
11.             }  
12.         } catch (IOException e) {  
13.             e.printStackTrace();  
14.         }  
15.   
16.     }  
17. }  

Java File Example 2

1. import java.io.*;  
2. public class FileDemo2 {  
3.     public static void main(String[] args) {  
4.   
5.         String path = "";  
6.         boolean bool = false;  
7.         try {  
29
UNIT V

8.             // createing  new files  
9.             File file  = new File("testFile1.txt");  
10.             file.createNewFile();  
11.             System.out.println(file);  
12.             // createing new canonical from file object  
13.             File file2 = file.getCanonicalFile();  
14.             // returns true if the file exists  
15.             System.out.println(file2);  
16.             bool = file2.exists();  
17.             // returns absolute pathname  
18.             path = file2.getAbsolutePath();  
19.             System.out.println(bool);  
20.             // if file exists  
21.             if (bool) {  
22.                 // prints  
23.                 System.out.print(path + " Exists? " + bool);  
24.             }  
25.         } catch (Exception e) {  
26.             // if any error occurs  
27.             e.printStackTrace();  
28.         }  
29.     }  
30. }  
Java File Example 3
1. import java.io.*;  
2. public class FileExample {  
3. public static void main(String[] args) {  
4.     File f=new File("/Users/NECG/Documents");  
5.     String filenames[]=f.list();  
6.     for(String filename:filenames){  
7.         System.out.println(filename);  
8.     }  
9. }  
10. }  

Java File Example 4

1. import java.io.*;  
2. public class FileExample {  
3. public static void main(String[] args) {  
4.     File dir=new File("/Users/NECG/Documents");  
5.     File files[]=dir.listFiles();  
6.     for(File file:files){  
7.         System.out.println(file.getName()+" Can Write: "+file.canWrite()+"   
8.         Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");  
9.     }  
10. }  
11. }  

30
UNIT V

Java - RandomAccessFile

 RandomAccessFile 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.

Constructor
Constructor Description

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

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

Example

1. import java.io.IOException;  
2. import java.io.RandomAccessFile;  
3.   
4. public class RandomAccessFileExample {  
5.     static final String FILEPATH ="myFile.TXT";  
6.     public static void main(String[] args) {  
7.         try {  
8.             System.out.println(new String(readFromFile(FILEPATH, 0, 18)));  
9.             writeToFile(FILEPATH, "I love my country and my people", 31);  
10.         } catch (IOException e) {  
11.             e.printStackTrace();  
12.         }  
13.     }  
14.     private static byte[] readFromFile(String filePath, int position, int size)  
15.             throws IOException {  
16.         RandomAccessFile file = new RandomAccessFile(filePath, "r");  
17.         file.seek(position);  
18.         byte[] bytes = new byte[size];  
19.         file.read(bytes);  
20.         file.close();  
21.         return bytes;  
22.     }  
23.     private static void writeToFile(String filePath, String data, int position)  
24.             throws IOException {  
25.         RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
26.         file.seek(position);  
27.         file.write(data.getBytes());  
28.         file.close();  
29.     }  
30. }  

31
UNIT V

The myFile.TXT contains text "This class is used for reading and writing to random access file."

*****END*****

32

You might also like