0% found this document useful (0 votes)
3 views24 pages

Java Unit-3 Threads& Util Packages

The document covers key concepts of threads in Java, including multitasking vs multithreading, thread lifecycle, thread creation methods, thread priorities, daemon threads, thread synchronization, and inter-thread communication. It explains the differences between multitasking and multithreading, outlines the states of a thread, and provides code examples for creating threads and implementing synchronization. Additionally, it discusses the importance of thread synchronization to prevent concurrency issues and describes inter-thread communication methods such as wait(), notify(), and notifyAll().
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)
3 views24 pages

Java Unit-3 Threads& Util Packages

The document covers key concepts of threads in Java, including multitasking vs multithreading, thread lifecycle, thread creation methods, thread priorities, daemon threads, thread synchronization, and inter-thread communication. It explains the differences between multitasking and multithreading, outlines the states of a thread, and provides code examples for creating threads and implementing synchronization. Additionally, it discusses the importance of thread synchronization to prevent concurrency issues and describes inter-thread communication methods such as wait(), notify(), and notifyAll().
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/ 24

Oops through java

UNIT-III

THREADS IN JAVA

Topics covered

 Multi-tasking and Multi-threading


 Thread Lifecycle
 How to create a thread
 Thread Priorities
 Daemon Thread
 Thread Synchronization
 Inter Thread Communication

Q1) Difference between multitasking and multithreading

Multi-Tasking or Multi Processing

 An operating system to run multiple processes or tasks concurrently,


sharing the same processor and other resources.
 It is a heavy weight process
 No communication between processors directly.
 In multitasking, the processes share separate memory locations.
 Multitasking is slow in comparison to multithreading.
 The process of termination takes more time

Multi Threading

 Multithreading allows the CPU to execute multiple threads of the same


process simultaneously.
 Thread is a light weight process
 In multithreading, the processes are allocated same memory.
 Multithreading is fast.
 The process of thread termination takes less time.
 Ex: Web Browser

Page 1 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Q2) THREAD LIFE CYCLE:

1. New State:
 When we create a thread object using the Thread class, the thread is
born and enters the New state. This means the thread is created, but the
start() method has not yet been called on the instance.

2. Runnable State:
 Runnable state means a thread is ready for execution of any statement.
When the start() method is called on a new thread, thread enters into
from New to a Runnable state.

 In runnable state, the thread is either running or ready to run and is


waiting for the availability of the processor (CPU time) for execution of
code. That is, thread has joined queue of threads that are waiting for
execution.
3. Running State:
 Running means Processor (CPU) has allocated time slot to thread for its
execution. When thread scheduler selects a thread from the runnable
state for execution, it goes into running state.

Page 2 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

4. Blocked State:
 A thread is considered to be in the blocked state when it is suspended,
sleeping, or waiting for some time in order to satisfy some condition.

 For example, a thread enters the Blocked state when it is waiting to


acquire a lock or a monitor that is held by another thread. This generally
happens when multiple threads are trying to access a synchronized block
or method.
5. Dead or Terminated State:
 A thread is terminated or dead when a thread comes out of run() method.

 A thread can also be dead when the stop() method is called. Once a
thread is in the DEAD state, it cannot be started again.

Thread Methods

Following is the list of important methods available in the Thread class.

Sr.No. Method & Description


public void start()
1
public void run()
2
public final void setName(String name)
3 Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
public final void setPriority(int priority)
4 Sets the priority of this Thread object. The possible values are between 1 and
10.
public final void setDaemon(boolean on)
5
A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the
6
current thread to block until the second thread terminates or the specified
number of milliseconds passes.
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was blocked for
any reason.
public final boolean isAlive()
8 Returns true if the thread is alive, which is any time after the thread has been
started but before it runs to completion.

Page 3 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Sr.No. Method & Description

public static void yield()


1 Causes the currently running thread to yield to any other threads of the same
priority that are waiting to be scheduled.

public static void sleep(long millisec)


2 Causes the currently running thread to block for at least the specified
number of milliseconds.

public static boolean holdsLock(Object x)


3
Returns true if the current thread holds the lock on the given Object.

public static Thread currentThread()


4 Returns a reference to the currently running thread, which is the thread that
invokes this method.

Q3) How to Create Threads in Java?

We can create Threads in java using two ways, namely :

1. Extending Thread Class

2. Implementing a Runnable interface

Write a java program to create a thread by Extending Thread Class


import java.io.*;
import java.util.*;

class MyThread extends Thread


{
public void run()
{
String str = "Thread Started Running...";
System.out.println(str);
}
}

public class program


{
public static void main(String args[])
Page 4 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

{
MyThread t1 = new MyThread();
t1.start();
}
}
Output
Thread Started Running...
Write a java program to create a thread by implementing runnable
interface

import java.io.*;
import java.util.*;

class MyThread implements Runnable


{
public void run()
{
String str = "Thread is Running Successfully";
System.out.println(str);
}
}
public class Program
{
public static void main(String[] args)
{
MyThread g1 = new MyThread();

Thread t1 = new Thread(g1);

t1.start();
}
}

Output
Thread is Running Successfully

Page 5 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

// Java Program to demonstrate usage of Thread class


Import java.io.*;
class MyThread extends Thread
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println(Thread.currentThread().getName()
+ " Count : " + i);

try
{
// Sleep for 500 milliseconds
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
}

public class Example


{
public static void main(String[] args)
{
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.setName("Thread 1");
thread2.setName("Thread 2");
thread1.start();
thread2.start();
}
}

Page 6 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

OUTPUT
Thread 1 - Count : 0
Thread 2 - Count : 0
Thread 1 - Count : 1
Thread 2 - Count : 1
Thread 1 - Count : 2
Thread 2 - Count : 2
Thread 1 - Count : 3
Thread 2 - Count : 3
Thread 2 - Count : 4
Thread 1 - Count : 4

Q4) THREAD PRIORITY

Built-in Property Constants of Thread Class

Java provides some handy constants for common priority levels. Let's take a
look:

Level Value Description

Thread.MIN_PRIORITY 1 Minimum priority

Thread.NORM_PRIORITY 5 Default/average priority

Thread.MAX_PRIORITY 10 Maximum priority

To set a thread's priority, we use the setPriority() method:

thread.setPriority(Thread.MAX_PRIORITY);

Page 7 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

THREAD PRIORITY WITH MULTIPLE THREASDS


import java.io.*;
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread());}
public static void main(String[] args)
{
A a = new A();
Thread t1 = new Thread(a, "First Thread");
Thread t2 = new Thread(a, "Second Thread");
Thread t3 = new Thread(a, "Third Thread");
t1.setPriority(4); // Setting priority of the first thread.
t2.setPriority(2); // Setting priority of the second thread.
t3.setPriority(8); // Setting priority of the third thread.
t1.start();
t2.start();
t3.start();
}
}
Output:
Thread[Third Thread,8,main]
Thread[First Thread,4,main]
Thread[Second Thread,2,main]

Q5)DAEMON THREAD IN JAVA

In Java, daemon threads are low-priority threads that run in the background
to perform tasks such as garbage collection or provide services to user threads.

Creating and Using Daemon Threads


To create a daemon thread, you can use the
setDaemon(boolean status) method of the Thread class.

This method marks the current thread as a daemon thread or user thread.
Here is an example:

Page 8 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

public class DaemonThread extends Thread


{
String s;
public DaemonThread(String name)
{
s=name;
}

public void run()


{
if (Thread.currentThread().isDaemon())
{
System.out.println(s+”is Daemon thread");
}
else
{
System.out.println( s+” is User thread");
}
}

public static void main(String[] args)


{
DaemonThread t1 = new DaemonThread("t1");
DaemonThread t2 = new DaemonThread("t2");
DaemonThread t3 = new DaemonThread("t3");
t1.setDaemon(true);
t1.start();
t2.start();
t3.setDaemon(true);
t3.start();
}
}
Output:
t1 is Daemon thread
t3 is Daemon thread
t2 is User thread
In this example, t1 and t3 are set as daemon threads, while t2 remains a user
thread.

Page 9 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Q6)THREAD SYNCHRONIZATION

When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues.

For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be
closing the same file.

So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time. This is
implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one thread
at a time may hold a lock on a monitor.

let’s try to solve the problem by using synchronized block

Program to show that with synchronization no problems will happen


when 2 passengers try to book train ticket, o when only 1 ticket was
available

Passenger1 Thread and Passenger2 Thread waited to book tickets.


Then Passenger1 Thread entered the synchronized block and acquired
object lock, but Passenger2 Thread wasn’t able to acquire object lock and
was waiting for Passenger1 Thread to release object lock.

By the time Passenger1 Thread was successfully able to book ticket and
reduce the available ticket count to 0, and then release object lock by
exiting synchronized block.

Than Passenger2 Thread got a chance to acquire object lock, but available
ticket count at that time was 0 so it wasn’t able to book ticket.

THREAD SYNCHRONIZATION PROGRAM:

import java.io.*;
class TicketBooking implements Runnable
{
int ticketsAvailable=1;
public void run()
{

Page 10 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

System.out.println("Waiting to book ticket for :


"+Thread.currentThread().getName());
synchronized (this)
{
if(ticketsAvailable>0)
{
System.out.println("Booking ticket for :
"+Thread.currentThread().getName());

//Let's say system takes some time in booking ticket (here we have taken
1 second time)
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
ticketsAvailable--;
System.out.println("Ticket BOOKED for : "+
Thread.currentThread().getName());
System.out.println("currently ticketsAvailable = "+ticketsAvailable);
}
else
{
System.out.println("Ticket NOT BOOKED for : "+
Thread.currentThread().getName());
}
}//End synchronization block
}
}
public class MyClass
{
public static void main(String args[])
{
TicketBooking obj=new TicketBooking();
Thread thread1=new Thread(obj,"Passenger1 Thread");
Thread thread2=new Thread(obj,"Passenger2 Thread");
thread1.start();
thread2.start();
}
}

Page 11 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

OUTPUT
Waiting to book ticket for : Passenger2 Thread

Waiting to book ticket for : Passenger1 Thread

Booking ticket for : Passenger2 Thread

Ticket BOOKED for : Passenger2 Thread

currently ticketsAvailable = 0

Ticket NOT BOOKED for : Passenger1 Thread

Write a program to print table of any number using Synchronized method.

class Table
{
synchronized void printTable(int n)
{
//synchronized method
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{ Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
Page 12 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

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

Page 13 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Q7) Inter-thread communication in Java (or) Consumer and Producer


Problem
Inter-thread communication is a mechanism that allows synchronized threads
to communicate with each other. This is crucial in scenarios where multiple
threads need to coordinate their actions, such as in a producer-consumer
problem.
Key Methods for Inter-Thread Communication

In Java, inter-thread communication is achieved using three primary methods


from the Object class: wait() , notify() , and notifyAll() 12.
 wait(): This method causes the current thread to release the lock and wait
until another thread invokes the notify() or notifyAll() method for the same
object. It can also be used with a timeout.
 notify(): This method wakes up a single thread that is waiting on the object's
monitor.
 notifyAll(): This method wakes up all the threads that are waiting on the
object's monitor.
These methods must be called within a synchronized block to ensure that the
thread holds the object's monitor.

Page 14 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

PROGRAM:

OUTPUT

GOING TO WITHDRAW
LESS BANCE
WAITING FOR DEPOSIT
GOINGTO DEPOSIT
DEPOSIT COMPLETED
WITHDRAW COMPLETED

Page 15 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

JAVA.UTIL PACKAGE- COLLECTION INTERFACES:

Java.util package- Collection Interfaces: List, Map, Set.

The Collection classes: LinkedList, HashMap, TreeSet, StringTokenizer, Date,


Random, Scanner

 List,
 Map,
 Set.
The Collection classes:
 LinkedList,
 HashMap,
 TreeSet,
 StringTokenizer,
 Date,
 Random,
 Scanner.

The Java collections framework provides a set of interfaces and classes to


implement various data structures and algorithms.

List

A list is an ordered collection of elements that can contain duplicates. Lists are
indexed, meaning each element has a specific position. They are useful for
maintaining sequences of items.

Map

A map is a collection of key-value pairs. Each key is unique, and it maps to a


specific value. Maps are ideal for situations where you need to associate values
with unique keys.

my_map = {'name': 'Alice', 'age': 25, 'city': 'Moinabad'}

Set

A set is an unordered collection of unique elements. Sets are useful for storing
items without duplicates and for performing mathematical set operations like
union, intersection, and difference.

Page 16 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Java Collections - List


A List is an ordered Collection of elements which may contain duplicates. It is
an interface that extends the Collection interface.
1. ArrayList
2.LinkedList
3.Vectors

Array list:
ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is
increased dynamically if the elements are added more than the initial size.
Syntax:
ArrayList object = new ArrayList ();

Example:
import java.util.*;
class DemoArrayList
{
public static void main(String args[])
{
ArrayList al=new ArrayList(); // creating array list
al.add("kmit"); // adding elements
al.add("Kmec");
al.add("501");
al.add("kmit");
al.set(1,"NGIT");
System.out.println(al.size());
System.out.println(al.indexOf("501"));
al.remove("kmit");
System.out.println(al.lastIndexOf("kmit"));
Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Linked List: Linked List is a sequence of links which contains items. Each link
contains a connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List

Linked List Example:


Page 17 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

import java.util.*;
public class DemoLinked
{
public static void main(String args[])
{
LinkedList<String> list=new LinkedList<String>();
//Adding elements to the Linked list
list.add("Sree");
list.add("Ram");
list.add("Raj");
//Adding an element to the first position
list.addFirst("KMIT");
//Adding an element to the last position
list.addLast("Sita");
//Adding an element to the 3rd position
list.add(2, "NGIT");
list.removeFirst();

//Removing Last element


list.removeLast();
list.remove(1);
//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
}
}

Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order. TreeSet allows null element
but like HashSet it doesn’t allow. Like most of the other collection classes this
class is also not synchronized.
Example:
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String args[])
{
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
// Adding elements to TreeSet<String>
tset.add("ABC");
tset.add("String");
Page 18 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");
//Displaying TreeSet
System.out.println(tset);
// TreeSet of Integer Type
TreeSet<Integer> tset2 = new TreeSet<Integer>();
// Adding elements to TreeSet<Integer>
tset2.add(88);
tset2.add(7);
tset2.add(101);
tset2.add(0);
tset2.add(3);
tset2.add(222);
System.out.println(tset2);
}
}
String Tokenizer:
StringTokenizer class is used for creating tokens in Java. It allows an
application to break or split into small parts. Each split string part is called
Token.
A StringTokennizer in Java, object keeps the string in the present position as it
is to be tokenized. By taking a substring of the string a token can return that
utilize to make the StringTokenizer protest.

Import java.util.*;
Page 19 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

public class StringTokenizerDemo {


public static void main(String args[])
{
System.out.println("StringTokenizer Constructor 1 - ");
StringTokenizer st1 =
new StringTokenizer("Hello Readers, Welcome to DataFlair", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("StringTokenizer Constructor 2 - ");
StringTokenizer st2 =
new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("StringTokenizer Constructor 3 - ");
StringTokenizer st3 =
new StringTokenizer("JAVA Code String", " : ", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}

BitSet:
Bitsets represents fixed size sequence of N bits having values either zero or
one. Zero means value is false or unset. One means value is true or set. Bitset
size is fixed at compile time. Bitset is a class defined in java.util package. It is a
special type of array which holds bit values. It implements a vector of bits. Its
size grows automatically as more bits are needed.

This class provides us two types of constructors to form bitset from integers as
well as from strings. Those two are:
Bitset( ): It is a no-argument constructor to create a default object.
Bitset(int size): It is a one-constructor having integer arguments to form an
instance of the bitset class with an initial size of the integer argument
representing the no. of bits.
Example:
import java.util.BitSet;
public class BitSetJavaExample
{
public static void main(String args[])
{
int n=8;
BitSet p = new BitSet(n);
for(int i=0;i<n;i++)
p.set(i);
System.out.print("Bits of p are set as : ");

Page 20 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
BitSet q = (BitSet) p.clone();
System.out.print("nBits of q are set as : ");
for(int i=0;i<n;i++)
System.out.print(q.get(i)+" ");
for(int i=0;i<3;i++)
p.clear(i);
System.out.print("nBits of p are now set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
System.out.print("nBits of p which are true : "+p);
System.out.print("The Bits of q which are true : "+q);
BitSet r= (BitSet) p.clone();
p.xor(q);
System.out.println("Output of p xor q= "+p);
p = (BitSet) r.clone();
p.and(q);
System.out.println("Output of p and q = "+p);
p = (BitSet) r.clone();
p.or(q);
System.out.println("Output of p or q = "+p);
}
}

Date class
Specify the desired pattern while creating the instance of SimpleDateFormat.
Create an object of Date class. Call the format() method of DateFormat class
and pass the date object as a parameter to the method.

DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");


Date dateobj = new Date();
System.out.println(df.format(dateobj));

Getting current date and time in other timezone


The example we have seen above shows the date and time in local timezone.
However we can get the date and time in different time zone as well such as
UTC/GMT etc. In the following example we are displaying the time in GMT time
zone.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Example
{
public static void main(String[] args)

Page 21 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

{
//"hh" in pattern is for 12 hour time format and "aa" is for AM/PM
SimpleDateFormat dateTimeInGMT = new SimpleDateFormat("yyyy-MMM-dd
hh:mm:ss aa");
//Setting the time zone
dateTimeInGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateTimeInGMT.format(new Date()));
}
}

Calendar class
Specify the desired pattern for the date and time. Similar to the step 1 of above
method. Create an object of Calendar class by calling getInstance() method of
it. Call the format() method of DateFormat and pass the Calendar.getTime() as
a parameter to the method.

DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");


Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
Complete java code for getting current date and time
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GettingCurrentDate
{
public static void main(String[] args)
{
//getting current date and time using Date class
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println(df.format(dateobj));
/*getting current date time using calendar class
* An Alternative of above*/
Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
}
}
Random
Java provides the Math class in the java.util package to generate random
numbers. The Math class contains the static Math.random() method to
generate random numbers of the double type.
The random() method returns a double value with a positive sign, greater than
or equal to 0.0 and less than 1.0. When you call Math.random(), under the

Page 22 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

hood, a java.util.Random pseudorandom-number generator object is created


and used.
You can use the Math.random() method with or without passing parameters. If
you provide parameters, the method produces random numbers within the
given parameters.

Formatter
Java Formatter is a utility class that can make life simple when working with
formatting stream output in Java. It is built to operate similarly to the C/C++
printf function. It is used to format and output data to a specific destination,
such as a string or a file output stream
Formatter Construction

Formatter(): It is a no-argument constructor to create a Formatter object. It


operates on a default buffer created from a StringBuilder. It is the commonly
used constructor of all of its type.

Formatter(Appendable a): Here, the Appendable object specifies a buffer for


formatted output. If, however, the value is null, the object automatically creates
a Stringbuilder to hold the formatted output.

Formatter(Appendable a, Locale loc): The Locale object regionalizes the


output format according to the specified locale. If unspecified, the default locale
is used. Sometimes, a locale is necessary to tailor the output according to Geo-
political or culturally sensitive data, such as formatting the date and time,
substituting a locale-specific decimal separator, and the like.

Formatter(File file): The file parameter of this constructor designates a


reference to a open file where the output will be streamed.
%S or %s: Specifies String
%X or %x: Specifies hexadecimal integer
%o: Specifies Octal integer
%d: Specifies Decimal integer
%c: Specifies character
%T or %t: Specifies Time and date
%n: Inserts newline character
%B or %b: Specifies Boolean
%A or %a: Specifies floating point hexadecimal
%f: Specifies Decimal floating point
Scanner
The Scanner class of the java.util package is used to read input data from
different sources like input streams, users, files, etc.
Example:

Page 23 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad
Oops through java

Read a Line of Text Using Scanner


import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
// Creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// Takes input from the keyboard
String name = input.nextLine();
// Prints name
System.out.println("My name is " + name);
// Closes the scanner
input.close();
}
}

Page 24 of 24
Dr K Venkata Subba Reddy, Professor, Vidya Jyothi Institute of Technology, Hyderabad

You might also like