0% found this document useful (0 votes)
2 views63 pages

Programming in Java-Unit IV

The document explains the Java Thread concept, which allows multiple tasks to run in parallel, enhancing program efficiency through multithreading. It details the thread life cycle, including states such as New, Active, Waiting, Timed Waiting, and Terminated, and describes how to create threads using either the Thread class or the Runnable interface. Additionally, it discusses thread priorities and methods for managing thread behavior in Java.

Uploaded by

Shameem Sulthana
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)
2 views63 pages

Programming in Java-Unit IV

The document explains the Java Thread concept, which allows multiple tasks to run in parallel, enhancing program efficiency through multithreading. It details the thread life cycle, including states such as New, Active, Waiting, Timed Waiting, and Terminated, and describes how to create threads using either the Thread class or the Runnable interface. Additionally, it discusses thread priorities and methods for managing thread behavior in Java.

Uploaded by

Shameem Sulthana
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/ 63

Java Thread

Before introducing the thread concept, we were unable to run more than one task in
parallel. It was a drawback, and to remove that drawback, Thread Concept was
introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the process
that allows a program to operate more efficiently by running multiple tasks
simultaneously.

In order to perform complicated tasks in the background, we used the Thread concept
in Java. All the tasks are executed without affecting the main program. In a program or
process, all the threads have their own separate path for execution, so each thread of a
process is independent.

Another benefit of using thread is that if a thread gets an exception or an error at the
time of its execution, it doesn't affect the execution of the other threads. All the threads
share a common memory and have their own stack, local variables and program
counter. When multiple threads are executed in parallel at the same time, this process is
known as Multithreading.

Backward Skip 10sPlay VideoForward Skip 10s

In a simple way, a Thread is a:

o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Java Thread model


Life Cycle Of Thread
There are different states Thread transfers into during its lifetime, let us know
about those states in the following lines: in its lifetime, a thread undergoes the
following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State
We can see the working of different states in a Thread in the above Diagram,
let us know in detail each and every state:
1. New State
By default, a Thread will be in a new state, in this state, code has not yet been
run and the execution process is not yet initiated.
2. Active State
A Thread that is a new state by default gets transferred to Active state when it
invokes the start() method, his Active state contains two sub-states namely:
 Runnable State: In This State, The Thread is ready to run at any given time
and it’s the job of the Thread Scheduler to provide the thread time for the
runnable state preserved threads. A program that has obtained
Multithreading shares slices of time intervals which are shared between
threads hence, these threads run for some short span of time and wait in the
runnable state to get their schedules slice of a time interval.
 Running State: When The Thread Receives CPU allocated by Thread
Scheduler, it transfers from the “Runnable” state to the “Running” state. and
after the expiry of its given time slice session, it again moves back to the
“Runnable” state and waits for its next time slice.
3. Waiting/Blocked State
If a Thread is inactive but on a temporary time, then either it is a waiting or
blocked state, for example, if there are two threads, T1 and T2 where T1 needs
to communicate to the camera and the other thread T2 already using a camera
to scan then T1 waits until T2 Thread completes its work, at this state T1 is
parked in waiting for the state, and in another scenario, the user called two
Threads T2 and T3 with the same functionality and both had same time slice
given by Thread Scheduler then both Threads T1, T2 is in a blocked state.
When there are multiple threads parked in a Blocked/Waiting state Thread
Scheduler clears Queue by rejecting unwanted Threads and allocating CPU on
a priority basis.
4. Timed Waiting State
Sometimes the longer duration of waiting for threads causes starvation, if we
take an example like there are two threads T1, T2 waiting for CPU and T1 is
undergoing a Critical Coding operation and if it does not exist the CPU until its
operation gets executed then T2 will be exposed to longer waiting with
undetermined certainty, In order to avoid this starvation situation, we had Timed
Waiting for the state to avoid that kind of scenario as in Timed Waiting, each
thread has a time period for which sleep() method is invoked and after the time
expires the Threads starts executing its task.
5. Terminated State
A thread will be in Terminated State, due to the below reasons:
 Termination is achieved by a Thread when it finishes its task Normally.
 Sometimes Threads may be terminated due to unusual events like
segmentation faults, exceptions…etc. and such kind of Termination can be
called Abnormal Termination.
 A terminated Thread means it is dead and no longer available.

How to Create Threads using Java Programming Language?


We can create Threads in java using two ways, namely :
1. Extending Thread Class
2. Implementing a Runnable interface
1. Creating a Thread by Extending Thread Class
We can run Threads in Java by using Thread Class, which provides
constructors and methods for creating and performing operations on a Thread,
which extends a Thread class that can implement Runnable Interface. We use
the following constructors for creating the Thread:
 Thread
 Thread(Runnable r)
 Thread(String name)
 Thread(Runnable r, String name)

Sample code to create Threads by Extending Thread Class:

import java.io.*;

import java.util.*;

public class GFG extends Thread {

// initiated run method for Thread

public void run()

System.out.println("Thread Started Running...");

public static void main(String[] args)

GFG g1 = new GFG();


// Invoking Thread using start() method

g1.start();

Output
Thread Started Running...

2.Creating a Thread by implementing Runnable Interface.


java.lang.Runnable is an interface that is to be implemented by a class whose
instances are intended to be executed by a thread. There are two ways to start
a new Thread – Subclass Thread and implement Runnable. There is no need of
subclassing a Thread when a task can be done by overriding only run() method
of Runnable.
Steps to create a new thread using Runnable
1. Create a Runnable implementer and implement the run() method.
2. Instantiate the Thread class and pass the implementer to the Thread, Thread
has a constructor which accepts Runnable instances.
3. Invoke start() of Thread instance, start internally calls run() of the
implementer. Invoking start() creates a new Thread that executes the code
written in run(). Calling run() directly doesn’t create and start a new Thread,
it will run in the same thread. To start a new line of execution, call start() on
the thread.
Example

public class RunnableDemo {

public static void main(String[] args)

System.out.println("Main thread is- "


+ Thread.currentThread().getName());

Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());

t1.start();

private class RunnableImpl implements Runnable {

public void run()

System.out.println(Thread.currentThread().getName()

+ ", executing run() method!");

Output:
Main thread is- main
Thread-0, executing run() method!
The output shows two active threads in the program – main thread and Thread-
0, main method is executed by the Main thread but invoking the start on
RunnableImpl creates and starts a new thread – Thread-0. What happens
when Runnable encounters an exception ? Runnable can’t throw checked
exception but RuntimeException can be thrown from the run(). Uncaught
exceptions are handled by the exception handler of the thread, if JVM can’t
handle or catch exceptions, it prints the stack trace and terminates the flow.
Thread Class

A thread is a program that starts with a method() frequently used in this class
only known as the start() method. This method looks out for the run() method
which is also a method of this class and begins executing the body of the run()
method. Here, keep an eye over the sleep() method which will be discussed
later below.
Note: Every class that is used as thread must implement Runnable interface
and over ride it’s run method.
Syntax:
public class Thread extends Object implements Runnable

Constructors of this class are as follows:

Constructor Action Performed

Thread() Allocates a new Thread object.

Thread(Runnable target) Allocates a new Thread object.

Thread(Runnable target, String


Allocates a new Thread object.
name)

Thread(String name) Allocates a new Thread object.

Thread(ThreadGroup group,
Allocates a new Thread object.
Runnable target)

Thread(ThreadGroup group, Allocates a new Thread object so that it has targeted


Runnable target, String name) as its run object, has the specified name as its name,
and belongs to the thread group referred to by a
Constructor Action Performed

group.

Allocates a new Thread object so that it has targeted


Thread(ThreadGroup group,
as its run object, has the specified name as its name,
Runnable target, String name,
and belongs to the thread group referred to by group,
long stackSize)
and has the specified stack size.

Thread(ThreadGroup group,
Allocates a new Thread object.
String name)

Methods of Thread class:

Now let us do discuss all the methods of this class are illustrated as follows:
Methods Action Performed

Returns an estimate of the number of active


activeCount() threads in the current thread’s thread group
and its subgroups

Determines if the currently running thread


checkAccess()
has permission to modify this thread

Throws CloneNotSupportedException as a
clone()
Thread can not be meaningfully cloned

currentThread() Returns a reference to the currently


Methods Action Performed

executing thread object

Prints a stack trace of the current thread to


dumpStack()
the standard error stream

Copies into the specified array every active


enumerate(Thread[] tarray) thread in the current thread’s thread group
and its subgroups

Returns a map of stack traces for all live


getAllStackTraces()
threads

Returns the context ClassLoader for this


getContextClassLoader()
Thread

Returns the default handler invoked when a


getDefaultUncaughtExceptionHandler() thread abruptly terminates due to an
uncaught exception

getId() Returns the identifier of this Thread

getName() Returns this thread’s name

getPriority() Returns this thread’s priority


Methods Action Performed

Returns an array of stack trace elements


getStackTrace()
representing the stack dump of this thread

getState() Returns the state of this thread

Returns the thread group to which this


getThreadGroup()
thread belongs

Returns the handler invoked when this


getUncaughtExceptionHandler() thread abruptly terminates due to an
uncaught exception

Returns true if and only if the current thread


holdsLock(Object obj) holds the monitor lock on the specified
object

interrupt() Interrupts this thread

Tests whether the current thread has been


interrupted()
interrupted

isAlive() Tests if this thread is alive

isDaemon() Tests if this thread is a daemon thread


Methods Action Performed

Tests whether this thread has been


isInterrupted()
interrupted

join() Waits for this thread to die

Waits at most millis milliseconds for this


join(long millis)
thread to die

If this thread was constructed using a


separate Runnable run object, then that
run() Runnable object’s run method is called;
otherwise, this method does nothing and
returns

setContextClassLoader(ClassLoader cl) Sets the context ClassLoader for this Thread

Marks this thread as either a daemon thread


setDaemon(boolean on)
or a user thread

Set the default handler invoked when a


setDefaultUncaughtExceptionHandler( thread abruptly terminates due to an
Thread.UncaughtExceptionHandler eh) uncaught exception, and no other handler
has been defined for that thread

Changes the name of this thread to be equal


setName(String name)
to the argument name.
Methods Action Performed

Set the handler invoked when this thread


setUncaughtExceptionHandler(
abruptly terminates due to an uncaught
Thread.UncaughtExceptionHandler eh)
exception

setPriority(int newPriority) Changes the priority of this thread

Causes the currently executing thread to


sleep (temporarily cease execution) for the
sleep(long millis) specified number of milliseconds, subject to
the precision and accuracy of system timers
and schedulers

Causes this thread to begin execution; the


start() Java Virtual Machine calls the run method of
this thread

Returns a string representation of this


toString() thread, including the thread’s name, priority,
and thread group

A hint to the scheduler that the current


yield() thread is willing to yield its current use of a
processor
Creating Multiple Threads in Java
Creating Multiple Threads in Java | In the previous all thread programs, we
have used only two threads: main thread, and one new thread (known as child
thread).
Now, we will learn methods of creating multiple threads in Java program.
Basically, when we need to perform several tasks at a time, we can create
multiple threads to perform multiple tasks in a program.
For example, to perform two tasks, we can create two threads and attach them
to two tasks. Hence, creating multiple threads in Java programming helps to
perform more than one task simultaneously.
Creating more than one thread to perform multiple tasks is
called multithreading in Java. In multiple threading programming, multiple
threads are executing simultaneously that improves the performance of CPU
because CPU is not idle if other threads are waiting to get some resources.
Multiple threads share the same address space in the heap memory.
Therefore, It is good to create multiple threads to execute multiple tasks rather
than creating multiple processes. Look at the below picture.
Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading
environment in which thread scheduler assigns the processor to a thread based on the
priority of thread. Whenever we create a thread in Java, it always has some priority
assigned to it. Priority can either be given by JVM while creating the thread or it can be
given by the programmer explicitly.
Priorities in threads is a concept where each thread is having a priority which in
layman’s language one can say every object is having priority here which is represented
by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 1.
 Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
Let us discuss it with an example to get how internally the work is getting executed. Here
we will be using the knowledge gathered above as follows:
 We will use currentThread() method to get the name of the current thread.
User can also use setName() method if he/she wants to make names of
thread as per choice for understanding purposes.
 getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.
Let us do discuss how to get and set priority of a thread in java.
1. public final int getPriority(): java.lang.Thread.getPriority() method returns
priority of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority()
method changes the priority of thread to the value newPriority. This method
throws IllegalArgumentException if value of parameter newPriority goes
beyond minimum(1) and maximum(10) limit.
Example
Java

// Java Program to Illustrate Priorities in Multithreading

// via help of getPriority() and setPriority() method


// Importing required classes

import java.lang.*;

// Main class

class ThreadDemo extends Thread {

// Method 1

// run() method for the thread that is called

// as soon as start() is invoked for thread in main()

public void run()

// Print statement

System.out.println("Inside run method");

// Main driver method

public static void main(String[] args)

{
// Creating random threads

// with the help of above class

ThreadDemo t1 = new ThreadDemo();

ThreadDemo t2 = new ThreadDemo();

ThreadDemo t3 = new ThreadDemo();

// Thread 1

// Display the priority of above thread

// using getPriority() method

System.out.println("t1 thread priority : "

+ t1.getPriority());

// Thread 1

// Display the priority of above thread

System.out.println("t2 thread priority : "

+ t2.getPriority());

// Thread 3

System.out.println("t3 thread priority : "


+ t3.getPriority());

// Setting priorities of above threads by

// passing integer arguments

t1.setPriority(2);

t2.setPriority(5);

t3.setPriority(8);

// t3.setPriority(21); will throw

// IllegalArgumentException

// 2

System.out.println("t1 thread priority : "

+ t1.getPriority());

// 5

System.out.println("t2 thread priority : "

+ t2.getPriority());
// 8

System.out.println("t3 thread priority : "

+ t3.getPriority());

// Main thread

// Displays the name of

// currently executing Thread

System.out.println(

"Currently Executing Thread : "

+ Thread.currentThread().getName());

System.out.println(

"Main thread priority : "

+ Thread.currentThread().getPriority());

// Main thread priority is set to 10

Thread.currentThread().setPriority(10);
System.out.println(

"Main thread priority : "

+ Thread.currentThread().getPriority());

Output

t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:
 Thread with the highest priority will get an execution chance prior to other
threads. Suppose there are 3 threads t1, t2, and t3 with priorities 4, 6, and 1.
So, thread t2 will execute first based on maximum priority 6 after that t1 will
execute and then t3.
 The default priority for the main thread is always 5, it can be changed later.
The default priority for all other threads depends on the priority of the parent
thread.
Now geeks you must be wondering out what if we do assign the same priorities
to threads then what will happen. All the processing in order to look after
threads is carried with help of the thread scheduler. One can refer to the below
example of what will happen if the priorities are set to the same and later
onwards we will discuss it as an output explanation to have a better
understanding conceptually and practically.
Applying Synchronization

Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.
Why use Java Synchronization?
Java Synchronization is used to make sure by some synchronization method that only one
thread can access the resource at a given point in time.

Java Synchronized Blocks

Java provides a way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized blocks
synchronize on the same object and can only have one thread executed inside them at a
time. All other threads attempting to enter the synchronized block are blocked until the
thread inside the synchronized block exits the block.
Note: Synchronized blocks in Java are marked with the synchronized keyword.

General Form of Synchronized Block

// Only one thread can execute at a time.


// sync_object is a reference to an object
// whose lock associates with the monitor.
// The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors or locks.
Only one thread can own a monitor at a given time. When a thread acquires a lock, it is
said to have entered the monitor. All other threads attempting to enter the locked monitor
will be suspended until the first thread exits the monitor.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization

1. Process Synchronization in Java

Process Synchronization is a technique used to coordinate the execution of multiple


processes. It ensures that the shared resources are safe and in order.

2. Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution of the threads
in a multi-threaded program. There are two types of thread synchronization are
mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
 Synchronized method.
 Synchronized block.
 Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:

// A Java program to demonstrate working of

// synchronized.

import java.io.*;

import java.util.*;
// A Class used to send a message

class Sender {

public void send(String msg)

System.out.println("Sending\t" + msg);

try {

Thread.sleep(1000);

catch (Exception e) {

System.out.println("Thread interrupted.");

System.out.println("\n" + msg + "Sent");

// Class for send a message using Threads

class ThreadedSend extends Thread {

private String msg;

Sender sender;
// Receives a message object and a string

// message to be sent

ThreadedSend(String m, Sender obj)

msg = m;

sender = obj;

public void run()

// Only one thread can send a message

// at a time.

synchronized (sender)

// synchronizing the send object

sender.send(msg);

}
// Driver class

class SyncDemo {

public static void main(String args[])

Sender send = new Sender();

ThreadedSend S1 = new ThreadedSend(" Hi ", send);

ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type

S1.start();

S2.start();

// wait for threads to end

try {

S1.join();

S2.join();

catch (Exception e) {
System.out.println("Interrupted");

Output

Sending Hi

Hi Sent
Sending Bye

Bye Sent
The output is the same every time we run the program.

Inter-thread communication
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.It is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()
wait() method
The 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.

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

Backward Skip 10sPlay VideoForward Skip 10s

Method Description

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

public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException

notify() method
The 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:

1. public final void notify()

notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()


Understanding the process of inter-thread
communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on 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.

Why wait(), notify() and notifyAll() methods are defined in Object


class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


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

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

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

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

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

Test.java

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...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Legacy Class in Java


In the past decade, the Collection framework didn't include in Java. In the early version
of Java, we have several classes and interfaces which allow us to store objects. After
adding the Collection framework in JSE 1.2, for supporting the collections framework,
these classes were re-engineered. So, classes and interfaces that formed the collections
framework in the older version of Java are known as Legacy classes. For supporting
generic in JDK5, these classes were re-engineered.

All the legacy classes are synchronized. The java.util package defines the
following legacy classes:

1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector

Working with Vector class


Vector is a special type of ArrayList that defines a dynamic array. ArrayList is not
synchronized while vector is synchronized. The vector class has several legacy methods
that are not present in the collection framework. Vector implements Iterable after the
release of JDK 5 that defines the vector is fully compatible with collections, and vector
elements can be iterated by the for-each loop.

Vector class provides the following four constructors:


1) Vector()

It is used when we want to create a default vector having the initial size of 10.

2) Vector(int size)

It is used to create a vector of specified capacity. It accepts size as a parameter to


specify the initial capacity.

3) Vector(int size, int incr)

It is used to create a vector of specified capacity. It accepts two parameters size and
increment parameters to specify the initial capacity and the number of elements to
allocate each time when a vector is resized for the addition of objects.

4) Vector(Collection c)

It is used to create a vector with the same elements which are present in the collection.
It accepts the collection as a parameter.

Example using Vector class


import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{
System.out.println(data.nextElement());
}
}
}

Output:

Understanding Stack class with example


Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor, which creates an empty stack. Stack includes
all the methods defined by Vector, and adds several of its own.

Stack( )

Apart from the methods inherited from its parent class Vector, Stack defines the
following methods −

Sr.No. Method & Description

boolean empty()
1
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack
contains elements.

2 Object peek( )
Returns the element on the top of the stack, but does not remove it.
3 Object pop( )
Returns the element on the top of the stack, removing it in the process.

4 Object push(Object element)


Pushes the element onto the stack. Element is also returned.

int search(Object element)


5
Searches for element in the stack. If found, its offset from the top of the stack is returned.
Otherwise, -1 is returned.

Example

The following program illustrates several of the methods supported by this collection −

Live Demo

import java.util.*;
public class StackDemo {

static void showpush(Stack st, int a) {


st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {


System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

This will produce the following result −

Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack

Introduction to Legacy Interfaces


Java versions earlier to Java2 did not contain any collections framework. They only
contained some classes and an interface, which were used to store objects. These are
called as Legacy classes and Legacy Interface. The Legacy classes are synchronized
as opposed to the classes in the collection framework. The Legacy classes are
Dictionary, Hashtable, Properties, Stack, and Vector. The Legacy interface is the
Enumeration interface.

Enumeration interface with example

The Enumeration interface defines the methods by which you can enumerate (obtain
one at a time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. Although not deprecated,
Enumeration is considered obsolete for new code. However, it is used by several
methods defined by the legacy classes such as Vector and Properties, is used by
several other API classes, and is currently in widespread use in application code.
The methods declared by Enumeration are summarized in the following table −

Sr.No. Method & Description

boolean hasMoreElements( )
1
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.

2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.

Example

Following is an example showing usage of Enumeration.

import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {


Enumeration days;
Vector dayNames = new Vector();

dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();

while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}
This will produce the following result −

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Introduction to Utility classes


Java.util Package

It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).
Following are the Important Classes in Java.util package :
1. AbstractCollection: This class provides a skeletal implementation of the Collection interface, to
minimize the effort required to implement this interface.
2. AbstractList: This class provides a skeletal implementation of the List interface to minimize the
effort required to implement this interface backed by a “random access” data store (such as an
array).
3. AbstractMap<K,V>: This class provides a skeletal implementation of the Map interface, to
minimize the effort required to implement this interface.
4. AbstractMap.SimpleEntry<K,V>: An Entry maintaining a key and a value.
5. AbstractMap.SimpleImmutableEntry<K,V>: An Entry maintaining an immutable key and value.
6. AbstractQueue: This class provides skeletal implementations of some Queue operations.
7. AbstractSequentialList: This class provides a skeletal implementation of the List interface to
minimize the effort required to implement this interface backed by a “sequential access” data store
(such as a linked list).
8. AbstractSet: This class provides a skeletal implementation of the Set interface to minimize the
effort required to implement this interface.
9. ArrayDeque: Resizable-array implementation of the Deque interface.
10. ArrayList: Resizable-array implementation of the List interface.
11. Arrays: This class contains various methods for manipulating arrays (such as sorting and
searching).
12. BitSet: This class implements a vector of bits that grows as needed.
13. Calendar: The Calendar class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next
week.
14. Collections: This class consists exclusively of static methods that operate on or return collections.
15. Currency: Represents a currency.
16. Date: The class Date represents a specific instant in time, with millisecond precision.
17. Dictionary<K,V>: The Dictionary class is the abstract parent of any class, such as Hashtable, which
maps keys to values.
18. EnumMap,V>: A specialized Map implementation for use with enum type keys.
19. EnumSet: A specialized Set implementation for use with enum types.
20. EventListenerProxy: An abstract wrapper class for an EventListener class which associates a set of
additional parameters with the listener.
21. EventObject: The root class from which all event state objects shall be derived.
22. FormattableFlags: FomattableFlags are passed to the Formattable.formatTo() method and modify
the output format for Formattables.
23. Formatter: An interpreter for printf-style format strings.
24. GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and provides the
standard calendar system used by most of the world.
25. HashMap<K,V>: Hash table based implementation of the Map interface.
26. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap
instance).
27. Hashtable<K,V>: This class implements a hash table, which maps keys to values.
28. IdentityHashMap<K,V>: This class implements the Map interface with a hash table, using
reference-equality in place of object-equality when comparing keys (and values).
29. LinkedHashMap<K,V>: Hash table and linked list implementation of the Map interface, with
predictable iteration order.
30. LinkedHashSet: Hash table and linked list implementation of the Set interface, with predictable
iteration order.
31. LinkedList: Doubly-linked list implementation of the List and Deque interfaces.
32. ListResourceBundle: ListResourceBundle is an abstract subclass of ResourceBundle that manages
resources for a locale in a convenient and easy to use list.
33. Locale – Set 1, Set 2: A Locale object represents a specific geographical, political, or cultural
region.
34. Locale.Builder: Builder is used to build instances of Locale from values configured by the setters.
35. Objects: This class consists of static utility methods for operating on objects.
36. Observable: This class represents an observable object, or “data” in the model-view paradigm.
37. PriorityQueue: An unbounded priority queue based on a priority heap.
38. Properties: The Properties class represents a persistent set of properties.
39. PropertyPermission: This class is for property permissions.
40. PropertyResourceBundle: PropertyResourceBundle is a concrete subclass of ResourceBundle that
manages resources for a locale using a set of static strings from a property file.
41. Random: An instance of this class is used to generate a stream of pseudorandom numbers.
42. ResourceBundle: Resource bundles contain locale-specific objects.
43. ResourceBundle.Control: ResourceBundle.Control defines a set of callback methods that are
invoked by the ResourceBundle.getBundle factory methods during the bundle loading process.
44. Scanner: A simple text scanner which can parse primitive types and strings using regular
expressions.
45. ServiceLoader: A simple service-provider loading facility.
46. SimpleTimeZone: SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone
for use with a Gregorian calendar.
47. Stack: The Stack class represents a last-in-first-out (LIFO) stack of objects.
48. StringTokenizer: The string tokenizer class allows an application to break a string into tokens.
49. Timer: A facility for threads to schedule tasks for future execution in a background thread.
50. TimerTask: A task that can be scheduled for one-time or repeated execution by a Timer.
51. TimeZone: TimeZone represents a time zone offset, and also figures out daylight savings.
52. TreeMap<K,V>: A Red-Black tree based NavigableMap implementation.
53. TreeSet: A NavigableSet implementation based on a TreeMap.
54. UUID: A class that represents an immutable universally unique identifier (UUID).
55. Vector: The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>: Hash table based implementation of the Map interface, with weak keys.

Working with StringTokenizer


1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple
way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.

Constructors of the StringTokenizer Class


There are 3 constructors defined in the StringTokenizer class.
Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

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

StringTokenizer(String str, String It creates StringTokenizer with specified string, delimiter and
delim, 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.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:
Methods Description

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

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

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

boolean hasMoreElements() It is the same as hasMoreTokens() method.

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

int countTokens() It returns the total number of tokens.

Example of StringTokenizer Class


Let's see an example of the StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.

Simple.java

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }

Output:

my
name
is
khan

The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().

Working with Date class

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.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date>


interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

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

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 returns an instance of Date object from Instant date.
instant)

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.

10) Instant toInstant() converts current date into Instant object.

11) String toString() converts this date into Instant object.

java.util.Date Example

Let's see the example to print date in java using java.util.Date class.

java.util.Date date=new java.util.Date();


System.out.println(date);

Output:

Wed Mar 27 08:22:02 IST 2015


Working with Calendar
The java.util.calendar class is an abstract class that provides methods for converting
between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.Following are the important points about Calendar

 This class also provides additional fields and methods for implementing a
concrete calendar system outside the package.
 Calendar defines the range of values returned by certain calendar fields.

Class declaration
Following is the declaration for java.util.Calendar class −

public abstract class Calendar

extends Object

implements Serializable, Cloneable, Comparable<Calendar>

Field
Following are the fields for java.util.Calendar class −

static int ALL_STYLES − This is the style specifier for getDisplayNames indicating names
in all styles, such as "January" and "Jan".

 static int AM − This is the value of the AM_PM field indicating


the period of the day from midnight to just before noon.
 static int AM_PM − This is the field number for get and set
indicating whether the HOUR is before or after noon.
 static int APRIL − This is the value of the MONTH field indicating
the fourth month of the year in the Gregorian and Julian
calendars.
 protected boolean areFieldsSet − This is true if fields[] are in
sync with the currently set time.
 static int AUGUST − This is the value of the MONTH field
indicating the eighth month of the year in the Gregorian and
Julian calendars.
 static int DATE − This is the field number for get and set
indicating the day of the month.
 static int DAY_OF_MONTH − This is the field number for get and
set indicating the day of the month.
 static int DAY_OF_WEEK − This is the field number for get and
set indicating the day of the week.
 static int DAY_OF_WEEK_IN_MONTH − This is the field number for
get and set indicating the ordinal number of the day of the
week within the current month.
 static int DAY_OF_YEAR − This is the field number for get and set
indicating the day number within the current year.
 static int DECEMBER − This is the value of the MONTH field
indicating the twelfth month of the year in the Gregorian and
Julian calendars.
 static int DST_OFFSET − This is the field number for get and set
indicating the daylight savings offset in milliseconds.
 static int ERA − This is the field number for get and set
indicating the era, e.g., AD or BC in the Julian calendar.
 static int FEBRUARY − This is the value of the MONTH field
indicating the second month of the year in the Gregorian and
Julian calendars.
 static int FIELD_COUNT − This is the number of distinct fields
recognized by get and set.
 protected int[] fields − This is the calendar field values for the
currently set time for this calendar.
 static int FRIDAY − This is the value of the DAY_OF_WEEK field
indicating Friday.
 static int HOUR − This is the field number for get and set
indicating the hour of the morning or afternoon.
 static int HOUR_OF_DAY − This is the field number for get and
set indicating the hour of the day.
 protected boolean[] isSet − This is the flags which tell if a
specified calendar field for the calendar is set.
 protected boolean isTimeSet − This is true if then the value of
time is valid.
 static int JANUARY − This is the value of the MONTH field
indicating the first month of the year in the Gregorian and
Julian calendars.
 static int JULY − This is the value of the MONTH field indicating
the seventh month of the year in the Gregorian and Julian
calendars.
 static int JUNE − This is the value of the MONTH field indicating
the sixth month of the year in the Gregorian and Julian
calendars.
 static int LONG − This is the style specifier for getDisplayName
and getDisplayNames indicating a long name, such as
"January".
 static int MARCH − This is the value of the MONTH field
indicating the third month of the year in the Gregorian and
Julian calendars.
 static int MAY − This is the value of the MONTH field indicating
the fifth month of the year in the Gregorian and Julian
calendars.
 static int MILLISECOND − This is the field number for get and set
indicating the millisecond within the second.
 static int MINUTE − This is the field number for get and set
indicating the minute within the hour.
 static int MONDAY − This is the value of the DAY_OF_WEEK field
indicating Monday.
 static int MONTH − This is the field number for get and set
indicating the month.
 static int NOVEMBER − This is the value of the MONTH field
indicating the eleventh month of the year in the Gregorian and
Julian calendars.
 static int OCTOBER − This is the value of the MONTH field
indicating the tenth month of the year in the Gregorian and
Julian calendars.
 static int PM − This is the value of the AM_PM field indicating
the period of the day from noon to just before midnight.
 static int SATURDAY − This is the value of the DAY_OF_WEEK
field indicating Saturday.
 static int SECOND − This is the field number for get and set
indicating the second within the minute.
 static int SEPTEMBER − This is the value of the MONTH field
indicating the ninth month of the year in the Gregorian and
Julian calendars.
 static int SHORT − This is the style specifier for getDisplayName
and getDisplayNames indicating a short name, such as "Jan".
 static int SUNDAY − This is the value of the DAY_OF_WEEK field
indicating Sunday.
 static int THURSDAY − This is the value of the DAY_OF_WEEK
field indicating Thursday.
 protected long time − This is the the currently set time for this
calendar, expressed in milliseconds after January 1, 1970,
0:00:00 GMT.
 static int TUESDAY − This is the value of the DAY_OF_WEEK
field indicating Tuesday.
 static int UNDECIMBER − This is the value of the MONTH field
indicating the thirteenth month of the year.
 static int WEDNESDAY − This is the value of the DAY_OF_WEEK
field indicating Wednesday.
 static int WEEK_OF_MONTH − This is the field number for get and
set indicating the week number within the current month.
 static int WEEK_OF_YEAR − This is the Field number for get and
set indicating the week number within the current year. .
 static int YEAR − This is the field number for get and set
indicating the year.
 static int ZONE_OFFSET − This is the field number for get and set
indicating the raw offset from GMT in milliseconds.
Class constructors
Sr.No. Constructor & Description

1 protected Calendar()
This constructor constructs a Calendar with the default time zone and locale.

2 protected Calendar(TimeZone zone, Locale aLocale)


This constructor constructs a calendar with the specified time zone and locale.

Class methods
Sr.No. Method & Description

abstract void add(int field, int amount)


1
This method adds or subtracts the specified amount of time to the given calendar field, based
on the calendar's rules.

boolean after(Object when)


2
This method returns whether this Calendar represents a time after the time represented by the
specified Object.

boolean before(Object when)


3
This method returns whether this Calendar represents a time before the time represented by
the specified Object.

void clear()
4
This method sets all the calendar field values and the time value (millisecond offset from the
Epoch) of this Calendar undefined.

void clear(int field)


5
This method sets the given calendar field value and the time value (millisecond offset from the
Epoch) of this Calendar undefined.

Object clone()
6
This method creates and returns a copy of this object.

int compareTo(Calendar anotherCalendar)


7
This method compares the time values (millisecond offsets from the Epoch) represented by
two Calendar objects.

protected void complete()


8
This method fills in any unset fields in the calendar fields.

protected abstract void computeFields()


9
This method converts the current millisecond time value time to calendar field values in
fields[].

protected abstract void computeTime()


10
This method converts the current calendar field values in fields[] to the millisecond time value
time.

boolean equals(Object obj)


11
This method compares this Calendar to the specified Object.
int get(int field)
12
This method returns the value of the given calendar field.

int getActualMaximum(int field)


13
This method returns the maximum value that the specified calendar field could have, given the
time value of this Calendar.

int getActualMinimum(int field)


14
This method returns the minimum value that the specified calendar field could have, given the
time value of this Calendar.

static Locale[] getAvailableLocales()


15
This method returns an array of all locales for which the getInstance methods of this class can
return localized instances.

String getDisplayName(int field, int style, Locale locale)


16
This method returns the string representation of the calendar field value in the given style and
locale.

Map<String,Integer> getDisplayNames(int field, int style, Locale locale)


17
This method returns a Map containing all names of the calendar field in the given style and
locale and their corresponding field values.

int getFirstDayOfWeek()
18
This method gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in
France.

abstract int getGreatestMinimum(int field)


19
This method returns the highest minimum value for the given calendar field of this Calendar
instance.

static Calendar getInstance()


20
This method gets a calendar using the default time zone and locale.

static Calendar getInstance(Locale aLocale)


21
This method gets a calendar using the default time zone and specified locale.

22 static Calendar getInstance(TimeZone zone)


This method gets a calendar using the specified time zone and default locale.

static Calendar getInstance(TimeZone zone, Locale aLocale)


23
This method gets a calendar with the specified time zone and locale.

abstract int getLeastMaximum(int field)


24
This method returns the lowest maximum value for the given calendar field of this Calendar
instance.

abstract int getMaximum(int field)


25
This method returns the maximum value for the given calendar field of this Calendar instance.

int getMinimalDaysInFirstWeek()
26 This method gets what the minimal days required in the first week of the year are; e.g., if the
first week is defined as one that contains the first day of the first month of a year, this method
returns 1.

abstract int getMinimum(int field)


27
This method returns the minimum value for the given calendar field of this Calendar instance.

Date getTime()
28
This method returns a Date object representing this Calendar's time value (millisecond offset
from the Epoch").

long getTimeInMillis()
29
This method returns this Calendar's time value in milliseconds.

TimeZone getTimeZone()
30
This method gets the time zone.

int hashCode()
31
This method Returns a hash code for this calendar.

protected int internalGet(int field)


32
This method returns the value of the given calendar field.

boolean isLenient()
33
This method tells whether date/time interpretation is to be lenient.
boolean isSet(int field)
34
This method determines if the given calendar field has a value set, including cases that the
value has been set by internal fields calculations triggered by a get method call.

abstract void roll(int field, boolean up)


35
This method adds or subtracts (up/down) a single unit of time on the given time field without
changing larger fields.

void roll(int field, int amount)


36
This method adds the specified (signed) amount to the specified calendar field without
changing larger fields.

void set(int field, int value)


37
This method sets the given calendar field to the given value.

void set(int year, int month, int date)


38
This method sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.

void set(int year, int month, int date, int hourOfDay, int minute)
39
This method sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH,
HOUR_OF_DAY, and MINUTE.

void set(int year, int month, int date, int hourOfDay, int minute, int second)
40
This method sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR,
MINUTE, and SECOND.

void setFirstDayOfWeek(int value)


41
This method sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in
France.

void setLenient(boolean lenient)


42
This method specifies whether or not date/time interpretation is to be lenient.

void setMinimalDaysInFirstWeek(int value)


43 This method sets what the minimal days required in the first week of the year are; For
Example, if the first week is defined as one that contains the first day of the first month of a
year, call this method with value.
void setTime(Date date)
44
This method sets this Calendar's time with the given Date.

void setTimeInMillis(long millis)


45
This method sets this Calendar's current time from the given long value.

void setTimeZone(TimeZone value)


46
This method sets the time zone with the given time zone value.

String toString()
47
This method return a string representation of this calendar.

Working with GregorianCalendar


GregorianCalendar is a hybrid calendar that supports both the Julian and
Gregorian calendar systems with the support of a single discontinuity, which
corresponds by default to the Gregorian date when the Gregorian calendar was
instituted.

The java.util.GregorianCalendar class in Java is a concrete subclass of Calendar


and provides the standard calendar system used by most of the world.

Import the following package to work with GregorianCalendar class.

import java.util.GregorianCalendar;
The following are the constructors.

Sr.No. Constructor & Description

GregorianCalendar()

1
This constructs a default GregorianCalendar using the current time in
the default time zone with the default locale.

GregorianCalendar(int year, int month, int dayOfMonth)

2
This constructs a GregorianCalendar with the given date set in the
default time zone with the default locale.

GregorianCalendar(int year, int month, int dayOfMonth, int


hourOfDay, int minute)
3
This constructs a GregorianCalendar with the given date and
time set for the default time zone with the default locale.

GregorianCalendar(int year, int month, int dayOfMonth, int


hourOfDay, int minute, int second)
4
This constructs a GregorianCalendar with the given date and time
set for the default time zone with the default locale.

GregorianCalendar(Locale aLocale)

5
This constructs a GregorianCalendar based on the current time in the
default time zone with the given locale.
Sr.No. Constructor & Description

GregorianCalendar(TimeZone zone)

This constructs a GregorianCalendar based on the current time in the


6 given time zone with the default locale.

GregorianCalendar(TimeZone zone, Locale aLocale)

7
This constructs a GregorianCalendar based on the current time in the
given time zone with the given locale.

Example

Live Demo

import java.util.GregorianCalendar;
public class Demo {
public static void main(String[] args) {
GregorianCalendar cal = (GregorianCalendar)
GregorianCalendar.getInstance();
System.out.println("" + cal.getTime());
}
}

Output
Mon Nov 19 15:57:40 UTC 2018

Working with Random Class

Java Random class


Java Random class is used to generate a stream of pseudorandom numbers. The
algorithms implemented by Random class use a protected utility method than can
supply up to 32 pseudorandomly generated bits on each invocation.

Methods
Methods Description

doubles() Returns an unlimited stream of pseudorandom double values.

ints() Returns an unlimited stream of pseudorandom int values.

longs() Returns an unlimited stream of pseudorandom long values.

next() Generates the next pseudorandom number.

nextBoolean() Returns the next uniformly distributed pseudorandom boolean value from the random number

nextByte() Generates random bytes and puts them into a specified byte array.

nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0 from the random number g

nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0 and 1.0 from
generator's sequence

nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0 and standard deviation
number generator's sequence.

nextInt() Returns a uniformly distributed pseudorandom int value generated from this random number g

nextLong() Returns the next uniformly distributed pseudorandom long value from the random number gen

setSeed() Sets the seed of this random number generator using a single long seed.
Example 1
1. import java.util.Random;
2. public class JavaRandomExample1 {
3. public static void main(String[] args) {
4. //create random object
5. Random random= new Random();
6. //returns unlimited stream of pseudorandom long values
7. System.out.println("Longs value : "+random.longs());
8. // Returns the next pseudorandom boolean value
9. boolean val = random.nextBoolean();
10. System.out.println("Random boolean value : "+val);
11. byte[] bytes = new byte[10];
12. //generates random bytes and put them in an array
13. random.nextBytes(bytes);
14. System.out.print("Random bytes = ( ");
15. for(int i = 0; i< bytes.length; i++)
16. {
17. System.out.printf("%d ", bytes[i]);
18. }
19. System.out.print(")");
20. }
21. }
Test it Now

Output:

Longs value : java.util.stream.LongPipeline$Head@14ae5a5


Random boolean value : true
Random bytes = ( 57 77 8 67 -122 -71 -79 -62 53 19 )

Working with Scanner Class

Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.

The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.

Java Scanner Class Declaration


1. public final class Scanner
2. extends Object
3. implements Iterator<String>

How to get Java Scanner


To get the instance of Java Scanner which reads input from the user, we need to pass
the input stream (System.in) in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner(System.in);

To get the instance of Java Scanner which parses the strings, we need to pass the strings
in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");


Java Scanner Class Constructors
SN Constructor Description

1) Scanner(File source) It constructs a new Scanner that produces valu


specified file.

2) Scanner(File source, String charsetName) It constructs a new Scanner that produces valu
specified file.

3) Scanner(InputStream source) It constructs a new Scanner that produces valu


specified input stream.

4) Scanner(InputStream source, String charsetName) It constructs a new Scanner that produces valu
specified input stream.

5) Scanner(Readable source) It constructs a new Scanner that produces valu


specified source.

6) Scanner(String source) It constructs a new Scanner that produces valu


specified string.

7) Scanner(ReadableByteChannel source) It constructs a new Scanner that produces valu


specified channel.

8) Scanner(ReadableByteChannel source, String It constructs a new Scanner that produces valu


charsetName) specified channel.

9) Scanner(Path source) It constructs a new Scanner that produces valu


specified file.

10) Scanner(Path source, String charsetName) It constructs a new Scanner that produces valu
specified file.
Java Scanner Class Methods
The following are the list of Scanner methods:

S Modifier Method Description


N & Type

1) void close() It is used to close this scanner.

2) pattern delimiter() It is used to get the Pattern which the Scanner class is currently
using to match delimiters.

3) Stream<M findAll() It is used to find a stream of match results that match the
atchResult provided pattern string.
>

4) String findInLine() It is used to find the next occurrence of a pattern constructed


from the specified string, ignoring delimiters.

5) string findWithinHorizon() It is used to find the next occurrence of a pattern constructed


from the specified string, ignoring delimiters.

6) boolean hasNext() It returns true if this scanner has another token in its input.

7) boolean hasNextBigDecimal( It is used to check if the next token in this scanner's input can be
) interpreted as a BigDecimal using the nextBigDecimal() method or
not.

8) boolean hasNextBigInteger() It is used to check if the next token in this scanner's input can be
interpreted as a BigDecimal using the nextBigDecimal() method or
not.

9) boolean hasNextBoolean() It is used to check if the next token in this scanner's input can be
interpreted as a Boolean using the nextBoolean() method or not.

10 boolean hasNextByte() It is used to check if the next token in this scanner's input can be
) interpreted as a Byte using the nextBigDecimal() method or not.

11 boolean hasNextDouble() It is used to check if the next token in this scanner's input can be
) interpreted as a BigDecimal using the nextByte() method or not.

12 boolean hasNextFloat() It is used to check if the next token in this scanner's input can be
) interpreted as a Float using the nextFloat() method or not.

13 boolean hasNextInt() It is used to check if the next token in this scanner's input can be
) interpreted as an int using the nextInt() method or not.

14 boolean hasNextLine() It is used to check if there is another line in the input of this
) scanner or not.

15 boolean hasNextLong() It is used to check if the next token in this scanner's input can be
) interpreted as a Long using the nextLong() method or not.

16 boolean hasNextShort() It is used to check if the next token in this scanner's input can be
) interpreted as a Short using the nextShort() method or not.

17 IOExceptio ioException() It is used to get the IOException last thrown by this Scanner's
) n readable.

18 Locale locale() It is used to get a Locale of the Scanner class.


)

19 MatchResu match() It is used to get the match result of the last scanning operation
) lt performed by this scanner.

20 String next() It is used to get the next complete token from the scanner which
) is in use.

21 BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.


)

22 BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.


)

23 boolean nextBoolean() It scans the next token of the input into a boolean value and
) returns that value.

24 byte nextByte() It scans the next token of the input as a byte.


)

25 double nextDouble() It scans the next token of the input as a double.


)

26 float nextFloat() It scans the next token of the input as a float.


)

27 int nextInt() It scans the next token of the input as an Int.


)

28 String nextLine() It is used to get the input string that was skipped of the Scanner
) object.

29 long nextLong() It scans the next token of the input as a long.


)

30 short nextShort() It scans the next token of the input as a short.


)

31 int radix() It is used to get the default radix of the Scanner use.
)

32 void remove() It is used when remove operation is not supported by this


) implementation of Iterator.

33 Scanner reset() It is used to reset the Scanner which is in use.


)

34 Scanner skip() It skips input that matches the specified pattern, ignoring
) delimiters

35 Stream<Str tokens() It is used to get a stream of delimiter-separated tokens from the


) ing> Scanner object which is in use.

36 String toString() It is used to get the string representation of Scanner using.


)

37 Scanner useDelimiter() It is used to set the delimiting pattern of the Scanner which is in
) use to the specified pattern.

38 Scanner useLocale() It is used to sets this scanner's locale object to the specified
) locale.

39 Scanner useRadix() It is used to set the default radix of the Scanner which is in use to
) the specified radix.

Examples using utility classes


Let's see a simple example of Java Scanner where we are getting a single input from the
user. Here, we are asking for a string through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }

Output:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal

You might also like