Unit - IV Notes (2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

PROGRAMMING USING JAVA

UNIT IV

Thread Concept in Java

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.

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.

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.

Thread Model

1) New (Ready to run)

A thread is in New when it gets CPU time.

2) Running
A thread is in a Running state when it is under execution.

3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under


execution.

4) Blocked

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution
immediately.

Creating Thread

A thread is created either by "creating or implementing" the Runnable


Interface or by extending the Thread class. These are the only two ways
through which we can create a thread.

Thread Class

A Thread class has several methods and constructors which allow us to


perform various operations on a thread. The Thread class extends
the Object class. The Object class implements the Runnable interface. The
thread class has the following constructors that are used to perform various
operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long
stackSize)

Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose


instances are intended to be executed by a thread. The runnable interface gives
us the run() method to perform an action for the thread.

start() method

The method is used for starting a thread that we have newly created. It starts a
new thread with a new callstack. After executing the start() method, the thread
changes the state from New to Runnable. It executes the run() method when
the thread gets the correct time to execute it.

Example Program:

// Implementing runnable interface by extending Thread class


public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
}
}

Output:

Creating thread by implementing the runnable interface

In Java, we can also create a thread by implementing the runnable interface. The
runnable interface provides us both the run() method and the start() method.

Example Program

class NewThread implements Runnable {


String name;
Thread thread;
NewThread (String name){
this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread+ "is created\n" );
thread.start();
}
public void run() {
try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " + j);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException excetion) {
System.out.println("Inturruption occurs in Main Thread");
}
System.out.println("We are exiting from Main Thread");
}
}

Output

How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.
Thread class:

Thread class provide constructors and methods to create and perform operations
on a thread.Thread class extends Object class and implements Runnable
interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently
executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended
thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances


are intended to be executed by a thread. Runnable interface have only one
method named run().

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

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It
performs the following tasks
Starting a thread:

The start() method of Thread class is used to start a newly created thread. It
performs the following tasks

1) Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:

thread is running...

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the
constructors defined above.

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)

Thread t= new Thread("My first thread");

// the start() method moves the thread to the active state


t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}

Output:

My first thread
Creating a Thread by implementing Runnable Interface

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


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

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

The runnable interface provides a standard set of rules for the instances of
classes which wish to execute code when they are active. The most common use
case of the Runnable interface is when we want only to override the run
method. When a thread is started by the object of any class which is
implementing Runnable, then it invokes the run method in the separately
executing thread.

Implementing Runnable

It is the easiest way to create a thread by implementing Runnable. One can


create a thread on any object by implementing Runnable. To implement a
Runnable, one has only to implement the run method.

public void run()

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


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

To create a thread using runnable, use the following code-

Runnable runnable = new MyRunnable();


Thread thread = new Thread(runnable);
thread.start();

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

Example

public class ExampleClass implements Runnable {

@Override
public void run() {
System.out.println("Thread has ended");
}

public static void main(String[] args) {


ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}

Output
Thread vs. Runnable

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


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

Assigning Thread priorities


The setPriority() method of thread class is used to change the thread's priority.
Every thread has a priority which is represented by the integer number between
1 to 10.

Thread class provides 3 constant properties:

1. public static int MIN_PRIORITY: It is the maximum priority of a


thread. The value of it is 1.
2. public static int NORM_PRIORITY: It is the normal priority of a
thread. The value of it is 5.
3. public static int MAX_PRIORITY: It is the minimum priority of a
thread. The value of it is 10.

Syntax

public final void setPriority(int a)

Parameter

a: It is the priority to set this thread to.

Return

It does not return any value.

Inter-thread Communication in Java

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()

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

Method Description

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


InterruptedException

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

2) 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:

public final void notify()

3) 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.

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


notifyAll() methods
completed.

Introduction to Legacy Classes- Working with Vector class

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

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:

Examples using Vector class


Vector is like the dynamic array which can grow or shrink its size. Unlike array,
we can store n-number of elements in it as there is no size limit.

Java Vector class Declaration


public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable

Example Program

import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}

Output
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Stack Class in Java


The stack is a linear data structure that is used to store the collection of objects. It
is based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
Empty Stack: If the stack has no element is known as an empty stack. When the
stack is empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following
figure,
o Push 12, top=0
o Push 6, top=1
o Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1. In the
following figure, we have popped 9.
Java Stack Class

In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable,
Cloneable, Serializable. It represents the LIFO stack of objects. Before using
the Stack class, we must import the java.util package.

Stack Class Constructor

The Stack class contains only the default constructor that creates an empty
stack.

public Stack()
Creating a Stack

If we want to create a stack, first, import the java.util package and create an
object of the Stack class.

Stack stk = new Stack();

Or

Stack<type> stk = new Stack<>();

Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class

We can perform push, pop, peek and search operation on the stack. The Java
Stack class provides mainly five methods to perform these operations. Along
with this, it also provides all the methods of the Java Vector class.

Method Modifi Method Description


er and
Type

empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top
of the stack.

pop() E The method removes an element from the top of the


stack and returns the same element as the value of that
function.

peek() E The method looks at the top element of the stack


without removing it.

search(Object int The method searches the specified object and returns
o) the position of the object.

Stack Class empty() Method

The empty() method of the Stack class check the stack is empty or not. If the
stack is empty, it returns true, else returns false. We can also use the isEmpty()
method of the Vector class.

Syntax

public boolean empty()

Stack Class push() Method

The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a
parameter item to be pushed into the stack.

Syntax

public E push(E item)

Parameter: An item to be pushed onto the top of the stack.

Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method

The method removes an object at the top of the stack and returns the same
object. It throws EmptyStackException if the stack is empty.
Syntax

public E pop()

Returns: It returns an object that is at the top of the stack.

Stack Class peek() Method

It looks at the element that is at the top in the stack. It also


throws EmptyStackException if the stack is empty.

Syntax

public E peek()

Returns: It returns the top elements of the stack.

Stack Class search() Method

The method searches the object in the stack from the top. It parses a parameter
that we want to search for. It returns the 1-based location of the object in the
stack. Thes topmost object of the stack is considered at distance 1.

Suppose, o is an object in the stack that we want to search for. The method
returns the distance from the top of the stack of the occurrence nearest the top of
the stack. It uses equals() method to search an object in the stack.

Syntax

public int search(Object o)

Parameter: o is the desired object to be searched.

Returns: It returns the object location from the top of the stack. If it returns -1,
it means that the object is not on the stack.
Java Collections enumeration() Method

The enumeration() is a method of Java Collections class which is used to get


the enumeration over the specified collection.

Syntax

Following is the declaration of enumeration() method:

public static <T> Eenumeration<T> enumeration(Collection<T> c)

Parameter

Parameter Description Required/Optional

c It is a collections for which Required


enumeration is to be returned.

Returns

The enumeration() method returns the enumeration over the specified


collection.

import java.util.*;
public class CollectionsEnumerationExample1 {
public static void main(String[] args) {
Vector<String> Enum = new Vector<String>();
Enum.add("JAVA");
Enum.add("JSP");
Enum.add("SERVLET");
Enum.add("C");
Enum.add("PHP");
Enum.add("PERL");
//Create Enumeration
Enumeration<String> en = Collections.enumeration(Enum);
System.out.println("The Enumeration List are: ");
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
}

Output:

The Enumeration List are:


JAVA
JSP
SERVLET
C
PHP
PERL

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

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

StringTokenizer in Java

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.

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

StringTokenizer(String str, It creates StringTokenizer with specified string,


String delim, boolean delimiter and returnValue. If return value is true,
returnValue) delimiter characters are considered to be tokens.
If it is false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class

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 It returns the next token based on the


delim) 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


import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

Output:

my
name
is
khan
Java Calendar Class

Java Calendar class is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable interface.

Java Calendar class declaration


public abstract class Calendar extends Object
implements Serializable, Cloneable, Comparable<Calendar>

List of Calendar Methods

No Method Description

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


field, int amount)
the given calendar field.

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

by when Object.

3. public boolean The method Returns true if the time represented


before(Object when)
by this Calendar is before the time represented by

when Object.

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

5. public Object Clone method provides the copy of the


clone()
current object.

6. public int The compareTo() method of Calendar class


compareTo(Calendar
compares
anotherCalendar)
the time values (millisecond offsets) between

two calendar object.

7. protected void It fills any unset fields in the calendar fields.


complete()

8. protected abstract It converts the current millisecond time


void
value time to calendar field values in fields[].
computeFields()

9. protected abstract It converts the current calendar field values


void computeTime()
in fields[] to the millisecond time value time.

10. public boolean The equals() method compares two objects


equals(Object
for equality and Returns true if they are equal.
object)

Java Calendar Class Example


import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}

Output:

The current date is : Thu Jan 19 18:47:02 IST 2017


15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

Working with GregorianCalendar- Working with Random Class

A concrete subclass of the Calendar class is referred to


as GregorianCalendar. The GregorianCalendar class has an implementation
of all of its inherited members. The Calendar class implements the mostly used
Gregorian calendar. In order to use the Gregorian calendar in Java, we import
the Java.util.GregorianCalendar class in our program.

Calendar cal = Calendar.getInstance();

The initialization of the cal object is done with the current date and time in the
default locale and timezone.
We can instantiate the GregorianCalendar class because of being a concrete
class.

GregorianCalendar gcal = new GregorianCalendar();

The initialization of the gcal object is done with the current date and time in the
default locale and timezone.

The anno Domini(AD) and the Before Christ(BC) are the two fields defined
by the GregorianCalendar 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.

Java Scanner Class Declaration


public final class Scanner
extends Object
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:

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:

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

Java Scanner Class Constructors

SN Constructor Description

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


values

scanned from the specified file.

2) Scanner(File source, String It constructs a new Scanner that produces


charsetName) values

scanned from the specified file.

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


values

scanned from the specified input stream.


4) Scanner(InputStream source, It constructs a new Scanner that produces
String charsetName) values

scanned from the specified input stream.

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


values

scanned from the specified source.

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


values

scanned from the specified string.

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


source) values

scanned from the specified channel.

8) Scanner(ReadableByteChannel It constructs a new Scanner that produces


source, String charsetName) values

scanned from the specified channel.

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


values

scanned from the specified file.

10) Scanner(Path source, String It constructs a new Scanner that produces


charsetName) values

scanned from the specified file.

Java Scanner Class Methods

The following are the list of Scanner methods:

SN Modifier & Type Method Description

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<MatchResult> findAll() It is used to find a stream


of match results

that match the 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.

Example
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

Output:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal

Examples using utility classes

The Collections utility class consists exclusively of static methods that operate
on or return collections. It contains polymorphic algorithms that operate on
collections, "wrappers", which return a new collection backed by a specified
collection,

import java.util.Collections;

import java.util.*;

public class CopyListDemo {

public static void main(String[] args) {

List <Integer>myFirstList = new ArrayList<Integer>();

List <Integer> mySecondList = new ArrayList<Integer>();


myFirstList.add(10);

myFirstList.add(20);

myFirstList.add(20);

myFirstList.add(50);

myFirstList.add(70);

mySecondList.add(11);

mySecondList.add(120);

mySecondList.add(120);

mySecondList.add(150);

mySecondList.add(170);

System.out.println("First List-"+ myFirstList);

System.out.println("Second List-"+ mySecondList);

Collections.copy(mySecondList, myFirstList );

System.out.println("Second List After Copy-"+ mySecondList);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy