0% found this document useful (0 votes)
3 views

JavaProgramming Unit-III

The document provides an introduction to Java I/O streams, explaining the concepts of InputStream and OutputStream, as well as byte and character stream classes. It also covers multithreading, detailing thread creation, lifecycle, synchronization, and inter-thread communication. Additionally, it introduces the Java Collection Framework, focusing on List and Set interfaces, their characteristics, and concrete implementations.

Uploaded by

anudeepmolugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JavaProgramming Unit-III

The document provides an introduction to Java I/O streams, explaining the concepts of InputStream and OutputStream, as well as byte and character stream classes. It also covers multithreading, detailing thread creation, lifecycle, synchronization, and inter-thread communication. Additionally, it introduces the Java Collection Framework, focusing on List and Set interfaces, their characteristics, and concrete implementations.

Uploaded by

anudeepmolugu
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/ 20

Unit-III

Chapter-1-Introduction to I/O streams


Java I/O (Input and Output) is used to process the input and produce the output.

 Java uses the concept of a stream to make I/O operation fast.


 The java.io package contains all the classes required for input and output operations.
 Stream is a sequence of data,stream is composed of bytes.
 Types of Pre defined Streams

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

OutputStream vs InputStream

OutputStream- Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.

InputStream- Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

java.io.* package supports two types


1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.

These two groups may further be classified based on their purpose.

Byte Stream Classes :


Byte stream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing bytes.

There are two kinds of byte stream classes :


• input stream classes and
• output stream classes.
Input Stream Classes :
The super class InputStream is an abstract class and therefore we cannot create instances of this class.
Rather, we must use the subclasses that inherit from this class. The InputStream class define methods for
performing input functions such as,

read(), read(byte b[]), read(byte b[], int n, int m), available(), skip(n), reset(), and close() methods.

Useful methods of InputStream


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

Output Stream Classes:


Output Stream classes are derived from the base class OutputStream. The OutputStream includes methods
that are designed to perform the following tasks:

write(), write(byte b[]), write(byte b[], int n, int m), close(), flush()

Useful methods of OutputStream


Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

File I/O:

Example of reading and writing bytes from one file to another file.

import java.io.*;

public class ByteFileExample


{
public static void main(String[] args)
{
File inFile = new File("Input.dat");
File outFile = new File("Output.dat");
FileInputStream ins = null; //Create File Stream for Reading
FileOutputStream outs = null; //Create File Stream for Writing
byte byteRead;
try
{
ins = new FileInputStream(inFile);
outs = new FileOutputStream(outFile);

while((byteRead = (byte) ins.read()) != -1)


outs.write(byteRead);
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e)
{}
} }}

Character Stream Classes :


Character streams can be used to read and write 16 bits unicode characters. There are two kinds of
character stream classes, namely,Reader stream classes and Writer stream classes.

Reader Stream Classes :

Reader stream classes are designed to read character from the files. Reader class is the base class for all
other classes in his group. The classes and methods are functionally very similar to the input stream classes.

Writer Stream Classes :

Like output stream classes, the writer stream classes are designed to perform all output operations on files.
only difference is that while output stream classes are designed to write bytes, the writer stream classes are
designed to write characters.
Example of reading and writing characters from one file to another file.

import java.io.*;

public class CharacterFileExample


{
public static void main(String[] args)
{
File inFile = new File("Input.dat");
File outFile new File("Output.dat");
FileReader ins = null; //Create File Stream for Reading
FileWriter outs = null; //Create File Stream for Writing

try
{
ins = new FileReader(inFile);
outs = new FileWriter(outFile);

int ch;
while((ch = ins.read()) != -1)
outs.write(ch);
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException e)
{}
}
}
}
Note : pls. refer lab programs on File I/O.
Chapter-2-Multi Threading
Multithreading is a feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread.
So, threads are light-weight processes within a process.

Thread vs Process
Process Thread
A program in execution is often referred as A thread is a subset(part) of the process. Hence
process. it is called lightweight process

A process consists of multiple threads. A thread is a smallest part of the process that
can execute concurrently with other
parts(threads) of the process

A process has its own address space A thread uses the process’s address space and
share it with the other threads of that process

A process can communicate with other process A thread can communicate with other thread
by using inter-process communication. (of the same process) directly by using
methods like wait(), notify(), notifyAll().

A process does not have control over the A process does not have control over the
sibling process, it has control over its child sibling process, it has control over its child
processes only. processes only.

Life cycle of a Thread (Thread States)

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states.

Creating Threads

Threads can be created by using two mechanisms :

1. Extending the Thread class


2. Implementing the Runnable Interface

 Thread creation by extending the Thread class

• We create a class that extends the java.lang.Thread class.


• This class overrides the run() method available in the Thread class.
• A thread begins its life inside run() method.
• start() is called to start the execution of a thread.
• start() invokes the run() method on the Thread object.

Example :

class MultithreadingDemo extends Thread


{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() + " is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}}}
output :

Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

 Thread creation by implementing the Runnable Interface

• create a class which implements java.lang.Runnable interface and override run()


method.
• Then instantiate a Thread object and call start() method on this object which
internally calls run( ) method to start child threads.

Example :
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +Thread.currentThread().getId()+”is running”);
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}}}
// Main class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}}}
OUTPUT:
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread Class vs Runnable Interface


• If we extend the Thread class, that class cannot extend any other class because java
doesn’t support multiple inheritance.
But, if we implement the Runnable interface, class can still extend other base classes.

• Thread class provides some inbuilt methods like yield(), interrupt() etc. that are not
available in Runnable interface, Runnable interface supports only run( ) method.

Thread Priority
 Each thread has a priority.
 Priorities are represented by a number between 1 and 10.
 Thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
3 Thread Priority constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.
Example :
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name
is:"+Thread.currentThread().getName()); System.out.println("running
thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();}}

Output:running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Thread Class Methods

various methods can be called on Thread class object. These methods are very
useful when writing a multithreaded application.

Thread Synchronization

 Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
 Synchronization is better option where we want to allow only one thread to access the
shared resource.

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Concept of Lock
 Synchronization is built around an internal entity known as the lock or monitor.
 Every object has a lock associated with it.
 A thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done
with them.
Example :
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);

}catch(Exception e){System.out.println(e);}
}}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5); } }
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}}
Output: 5
100
10
200
15
300
20
400
25
500
With synchronized method

 If you declare any method as synchronized, it is known as synchronized method.


 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.

class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}}
public class TestSynchronization2
{
public static void main(String args[]) {
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }
Output: 5
10
15
20
25
100
200
300
400
500
Inter-thread communication

Inter-thread communication or Co-operation is about allowing synchronized threads to


communicate with each other.
o Inter-thread communication is a mechanism in which a thread is paused running in its
critical section and
o Another thread is allowed to enter (or lock) in the same critical section to be executed.
Inter Thread communication is implemented by the following methods
1. wait() 2. notify() 3. notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
Syntax: public final void wait()throws InterruptedException

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax: public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll().

Chapter-3-java.util.package
The Collection framework represents a unified architecture for storing and manipulating a
group of objects.

It supports List & Set Interfaces

List Interface
 This interface represents a collection of elements whose elements are arranged in
sequentially ordered.
 List maintains an ordered of elements means the order is retained in which we add
elements
 We can insert elements into the list at any location.
 The list allows storing duplicate elements in Java.
 ArrayList, vector, and LinkedList are three concrete subclasses which implement
list interface.

Set Interface
 This interface represents a collection of elements that contains unique elements.
 Set interface does not maintain any order while storing elements and while
retrieving, we may not get the same order as we put elements.
 Set does not allow any duplicate elements.
 HashSet, LinkedHashSet, TreeSet classes implements the set interface

SortedSet Interface
 This interface extends a set whose iterator transverse its elements according to
their natural ordering.
 TreeSet implements the sorted interface.

Map Interface

 Map interface is not inherited by the collection interface.


 It represents an object that stores and retrieves elements in the form of a
Key/Value pairs and their location within the Map are determined by a Key.
 Map uses a hashing technique for storing key-value pairs.
 It doesn’t allow to store the duplicate keys but duplicate values are allowed.
 HashMap, HashTable, LinkedHashMap, TreeMap classes implements Map
SortedMap Interface
This interface represents a Map whose elements are stored in their natural
ordering. It extends the Map interface which in turn is implemented by TreeMap
classes.

LinkedList class
LinkedList class uses a doubly linked list to store the elements.
o LinkedList class can contain duplicate elements.
o LinkedList class maintains insertion order.
o LinkedList class is non synchronized.
o LinkedList class can be used as a list, stack or queue.

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the elements of the


extends E> c) specified collection, in the order, they are returned by the
collection's iterator.

Methods of LinkedList (E-element object)


Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int It is used to insert the specified element at the specified


index, E position index in a list.
element)
void It is used to insert the given element at the beginning of a
addFirst(E e) list.
void It is used to append the given element to the end of a list.
addLast(E e)
void clear() It is used to remove all the elements from a list.

E get(int index) It is used to return the element at the specified position in a


list.
E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

import java.util.*;
public class LinkedList1{
public static void main(String args[])
{
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
System.out.println("After adding elements to the list: "+ll);
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
}
}

OUTPUT:
Initial list of elements: []
After adding elements to the list: [Ravi, Vijay, Ravi, Ajay] After invoking addFirst(E e) method:
[Lokesh, Ravi, Vijay, Ravi, Ajay]
After invoking remove(object) method: [Lokesh, Ravi, Ravi, Ajay]

HashMap class

HashMap class implements the map interface by using a hash table. It inherits AbstractMap class
and implements Map interface

 Map class contains values based on the key.


 HashMap class contains only unique keys.
 HashMap class may have one null key and multiple null values.
 HashMap class is non synchronized.
 HashMap class maintains no order.
 The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Constructors of HashMap class

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map<? extends K,? extends It is used to initialize the hash map by using the elements of the given
V> m) Map object m.
It is used to initializes the capacity of the hash map to the given
HashMap(int capacity)
integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of the hash
loadFactor) map by its arguments.

Methods of Java using HashMap class


Method Description
It is used to remove all of the mappings from this
void clear()
map.
It is used to return true if this map contains no
boolean isEmpty()
key-value mappings.
It is used to return a shallow copy of this
Object clone() HashMap instance: the keys and values
themselves are not cloned.
It is used to return a collection view of the
Set entrySet()
mappings contained in this map.
It is used to return a set view of the keys
Set keySet()
contained in this map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
It inserts the specified value with the specified
V putIfAbsent(K key, V value)
key in the map only if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
This method returns the object that contains the
V get(Object key)
value associated with the key.
This method returns true if the map is empty;
boolean isEmpty()
returns false if it contains at least one key.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, It replaces the old value with the new value for a
V newValue) specified key.
It replaces each entry's value with the result of
void replaceAll(BiFunction<? super invoking the given function on that entry until all
K,? super V,? extends V> function) entries have been processed or the function throws
an exception.
It returns a collection view of the values contained
Collection<V> values()
in the map.
This method returns the number of entries in the
int size()
map.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

Example:

 import java.util.*;
 class Book {
 int id;
 String name,author,publisher;
 int quantity;
 public Book(int id, String name, String author, String publisher, int quantity) {
 this.id = id;
 this.name = name;
 this.author = author;
 this.publisher = publisher;
 this.quantity = quantity;
 }
 }
 public class MapExample {
 public static void main(String[] args) {
 //Creating map of Books
 Map<Integer,Book> map=new HashMap<Integer,Book>();
 //Creating Books
 Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
 Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
 Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
 //Adding Books to map
 map.put(1,b1);
 map.put(2,b2);
 map.put(3,b3);
 //Traversing map
 for(Map.Entry<Integer, Book> entry:map.entrySet()){
o int key=entry.getKey();
o Book b=entry.getValue();
o System.out.println(key+" Details:");
o System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
 }
 }
 }

Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

TreeSet class

o TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. TreeSet class contains
unique elements only like HashSet.
o TreeSet class access and retrieval times are quiet fast.
o TreeSet class doesn't allow null element.
o TreeSet class is non synchronized.
o TreeSet class maintains ascending order.

Constructors
Constructor Description
It is used to construct an empty tree set that will be sorted in ascending
TreeSet()
order according to the natural order of the tree set.
TreeSet(Collection<? extends E> It is used to build a new tree set that contains the elements of the
c) collection c.
TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according to
comparator) given comparator.
It is used to build a TreeSet that contains the elements of the given
TreeSet(SortedSet<E> s)
SortedSet.
Methods
Method Description
It is used to add the specified element to this set if it is not already
boolean add(E e)
present.
boolean addAll(Collection<? extends It is used to add all of the elements in the specified collection to
E> c) this set.
E pollFirst() It is used to retrieve and remove the lowest(first) element.
E pollLast() It is used to retrieve and remove the highest(last) element.
boolean isEmpty() It returns true if this set contains no elements.
It is used to remove the specified element from this set if it is
boolean remove(Object o)
present.
void clear() It is used to remove all of the elements from this set.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
int size() It returns the number of elements in this set.

Example
import java.util.*;
class TreeSetDemo{
public static void main(String args[]){
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(24);
set.add(66);
set.add(12);
set.add(15);
System.out.println("Highest Value: "+set.pollFirst());
System.out.println("Lowest Value: "+set.pollLast());
}
}

OUTPUT:
Highest Value: 12
Lowest Value: 66

StringTokenizer class
 StringTokenizer class in Java is used to break a string into tokens.
Constructors

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

Methods
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

Example:
import java.util.StringTokenizer;
public class STDemo{
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

Date class

 The java.util.Date class represents date and time in java.


 It provides constructors and methods to deal with date and time in java.

Constructors:
Constructo Description
r
Date() Creates a date object representing current date and time.

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

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

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

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

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

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

Example:

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


System.out.println(date);
Output :Wed Mar 27 08:22:02 IST 2015

Random class
Java Random class is used to generate a stream of pseudo random numbers.

Constructors:

Random(): Creates a new random number generator

Random(long seed): Creates a new random number generator using a single long seed

Methods
Methods Description
next() Generates the next pseudorandom number.
nextBoolean() Returns the next uniformly distributed pseudorandom boolean value
from the random number generator's sequence
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 generator's sequence
nextFloat() Returns the next uniformly distributed pseudorandom Float value
between 0.0 and
1.0 from this random number generator's sequence
nextInt() Returns a uniformly distributed pseudorandom int value generated
from this random number generator's sequence
nextLong() Returns the next uniformly distributed pseudorandom long value
from the random number generator's sequence.
Example:
import java.util.Random;
public class JavaRandomExample2 {
public static void main(String[] args) {
Random random = new Random();
//return the next pseudorandom integer value
System.out.println("Random Integer value : "+random.nextInt());
// setting seed
long seed =20;
random.setSeed(seed);
//value after setting seed
System.out.println("Seed value : "+random.nextInt());
//return the next pseudorandom long value
Long val = random.nextLong();
System.out.println("Random Long value : "+val);
}}
Output: Random Integer value : 1294094433
Seed value : -1150867590
Random Long value : -7322354119883315205
Scanner Class
 Scanner class is used to read the data from the keyboard
 The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default.

Constructor :
Scanner in = new Scanner(System.in);

Few of the Scanner class methods:

Modifier &
Method Description
Type
Boolean hasNext() It returns true if this scanner has another token in its input.
String next() It is used to get the next complete token from the scanner which is in use.
It scans the next token of the input into a boolean value and returns that
Boolean nextBoolean()
value.
Byte nextByte() It scans the next token of the input as a byte.
Double nextDouble() It scans the next token of the input as a double.
Float nextFloat() It scans the next token of the input as a float.
Int nextInt() It scans the next token of the input as an Int.
String nextLine() It is used to get the input string that was skipped of the Scanner object.
Long nextLong() It scans the next token of the input as a long.
Short nextShort() It scans the next token of the input as a short.
String toString() It is used to get the string representation of Scanner using.
Example:
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your college name: ");
String name = in.nextLine();
System.out.println("College Name is: " + name);
in.close();
} } output: Enter your college name: vjit
College Name is: vjit

You might also like