Sunteți pe pagina 1din 24

UNIT 3

Introduction – Life Cycle of Thread-Creating and Running Threads-Methods in Thread Class-


Setting the Priority of a Thread-Synchronization.

INTRODUCTION:
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process have its own address in memory i.e. each process allocates separate
memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
 Cost of communication between the thread is low.
What is Thread in java
A thread is an independent path of execution within a program. Many threads can run
concurrently within a program. Every thread in Java is created and controlled by
the java.lang.Thread class.
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one process
can have multiple threads. .At a time one thread is executed only.

Multithreading
 Multithreading in java is a process of executing multiple threads simultaneously.
 Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading both are used to achieve multitasking.
 But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation etc.

Advantage of Java Multithreading


 It doesn't block the user because threads are independent and we can perform multiple
operations at same time.
 We can perform many operations together so it saves time.
 Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Life cycle of a Thread (Thread States):


A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 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

New
The thread is in new state if we create an instance of Thread class but before the
invocation of start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method exits.

How to Create Thread


There are two ways to create a thread:
1. By Extending Thread class
2. By Implementing Runnable interface.
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().
public void run(): is used to perform action for a thread

Starting a thread:
 start() method of Thread class is used to start a newly created thread. It
performs following tasks:
 A new thread starts (with new callstack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
1. By Extending Thread Class
 When the class extends a Tread class, it must override run() method of the
Thread class.
 Must supply a public void run() method
 Start a thread by invoking the start() method
 When a thread starts, it executes run()
 When run() returns, thread is finished/dead
Syntax:
class classname extends Thread
{
public void run ( ) //must override
{
}
}
public class classname
{
public static void main( String args[])
{
classname objname = new classname ();
objname.start () ;
}
}
Example Program:
class Multi extends Thread
{
Multi(int a) //Parameterized Constructor
{
System.out.println("Result" +a);
}
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(100);
t1.start();
}
}

Output :

Result 100
Thread is running...

Who makes your class object as thread object?


Thread class constructor allocates a new thread object. When you create object of Multi
class, your class constructor is invoked (provided by Compiler) from where Thread class
constructor is invoked (by super() as first statement).So your Multi class object is thread object
now.

2.By Implementing Runnable interface:

 A Thread can be created by extending Thread class also. But Java allows only one class
to extend, it won’t allow multiple inheritance. So it is always better to create a thread
by implementing Runnable interface. Java allows you to implement multiple interfaces
at a time.
 By implementing Runnable interface, you need to provide implementation for run()
method.
 To run this implementation class, create a Thread object, pass Runnable
implementation class object to its constructor. Call start() method on thread class to
start executing run() method.
 Implementing Runnable interface does not create a Thread object, it only defines an
entry point for threads in your object. It allows you to pass the object to the Thread
(Runnable implementation) constructor.

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);
t1.start();
}
}

Output:
Thread is running…

If you are not extending the Thread class, your class object would not be treated as a
thread object. So you need to explicitly create Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
Sleep method

The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
Syntax:
sleep()
The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws
InterruptedException

class Test extends Thread


{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Test t1=new Test();
Test t2=new Test();
t1.start();
t2.start();
}
}

As we know well that at a time only one thread is executed. If we sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.

Output
1
1
2
2
3
3
4
4
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:

 Thread() -This allocates a new Thread object.


 Thread(Runnable target) - This allocates a new Thread object.
 Thread(Runnable target, String name)-This allocates a new Thread object.
 Thread(String name)-This constructs allocates a new Thread object.
 Thread(ThreadGroup group, Runnable target)-This allocates a new Thread
object.
 Thread(ThreadGroup group, Runnable target, String name)-This allocates a
new Thread object so that it has target as its run object, has the specified name as
its name, and belongs to the thread group referred to by group.
 Thread(ThreadGroup group, Runnable target, String name, long stackSize)-
This allocates a new Thread object so that it has target as its run object, has the
specified name as its name, belongs to the thread group referred to by group, and has
the specified stack size.
 Thread(ThreadGroup group, String name) -This allocates a new Thread object.

Methods in 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.
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

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


and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
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:1
running thread name is:Thread-1
running thread priority is:10

Synchronization:
At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred to
as critical section.(or) Synchronization in java is the capability to control the access of multiple
threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
Every Java object with a critical section of code gets a lock associated with the object. To
enter critical section a thread need to obtain the corresponding object's lock.
General Syntax :
Synchronized (object)
{
// statement to be synchronized
}
Here ,object is a reference to the object being synchronized.
Why we use Synchronization ?
The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

If we do not use synchronization, and let two or more threads access a shared resource at
the same time, it will lead to distorted results.
Consider an example, suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file temporary.txt which will be used to calculate some
result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved
by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will
return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in
above case, once T1 starts using temporary.txt file, this file will be locked (LOCK mode), and no
other thread will be able to access or modify it until T1 returns.
Types of Synchronization

There are two types of synchronization


1. Thread Synchronization
2. Process Synchronization
1. Thread Synchronization
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)

1.Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
i. by synchronized method
ii. by synchronized block
iii. by static synchronization

1.Java synchronized method

 If we can 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);
}
}
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

2.Java synchronized Block:


 Synchronized block can be used to perform synchronization on any specific resource of
the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax
synchronized (object reference expression)
{ //code block
}
Example :

class Table
{
void printTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
} //end of the method
}
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 TestSynchronizedBlock1
{
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

Text and Binary formats of Data

In Java the files are viewed as sequential streams of bytes. Stream itself is sequence of data.when
building program in Java we often need to interact with out side world, i.e files,network streams
etc, Or when we want to store the state of the object we need to interact with these out side world
.

There are two types of files that we will use.


Byte-Based
character Based.

Byte-Based Files(BInay Files)

These files are also called binary files. Because when the data is taken as input or shown as
output is in format of binary.For example, if we store the value 6, it would be stored in the binary
format of 110=6. And this value can be used as integer for calculation purpose.
 Can not be understood by humans .
 The binary files are read by the Java programs .
 We use InputStream and OutPutStream classes when dealing with bytebased data.

Character-Based files(Text Files)

These files are also called text files. Because when the data is taken as input or shown as output,
is in format of sequence of character.

 The data in the file can be easily understood by humans.


 The character based files are read by text-editor.
 Writer and Reader classes are used when dealing with character based data.

IO Stream

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.

Java encapsulates Stream under java.io package. Java defines two types of streams. They are,

Byte Stream : It provides a convenient means for handling input and output of byte.
Character Stream : It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream
and OutputStream.These two abstract classes have several concrete classes that handle various
devices such as disk files, network connection etc.

Byte stream classification

Some important Byte stream classes are:

Stream class Description

BufferedInputStream Used for Buffered Input Stream.


BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

Methods
read() : reads byte of data.
write() : Writes byte of data.

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.

Java DataOutputStream class methods

Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v)It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte
value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.

Example of DataOutputStream class


In this example, we are writing the data to a text file testout.txt using DataOutputStream class.

import java.io.*;
public class OutputExample
{
public static void main(String[] args) throws IOException
{
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in
a machine-independent way.Java application generally uses the data output stream to write data
that can later be read by a data input stream.

public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream class Methods

Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero,
false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the
buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.

Example of DataInputStream class


In this example, we are reading the data from the file testout.txt file.
import java.io.*;
public class DataStreamExample
{
public static void main(String[] args) throws IOException
{
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.

Java DataOutputStream class methods

Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v)It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte
value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of
bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
encoding in portable manner.
void flush() It is used to flushes the data output stream.

Example of DataOutputStream class


In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
import java.io.*;
public class OutputExample
{
public static void main(String[] args) throws IOException
{
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A

Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
character stream classification

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

Some important Charcter stream classes.


Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

BufferedReader class explanation

Reading Characters

read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.

class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings

To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Program to take String input from Keyboard in Java

import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Reading File Input

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Program to write to a File using FileWriter class
import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

StreamTokenizer

For StreamTokenizer, the source is a character stream, Reader. StreamTokenizer tokenizes the
stream into distinct words and allows to read one by one. It is not a general tokenizer and
includes the capability of knowing the type of the token like the token is a word or number. For
general tokenization, there comes java.util.Scanner where each word or line can read with next(),
nextLine() and nextUTF() methods. StreamTokenizer includes a method nextToken() that can be
used in a for loop to print all the tokens.

The StreamTokenizer comes with the following constant variables (instance variables are also
known as fields) used to decide the type of the token.

int ttype: When the nextToken() returns a token, this field can be used to decide the type of the
token.
static final int TT_EOF: This field is used to know the end of file is reached.
static final int TT_EOL: This field is used to know the end of line is reached.
static final int TT_NUMBER: This field is used to decide the token returned by the
nextToken() method is a number or not.
static final int TT_WORD: This field is used to decide the token returned by the nextToken()
method is a word or not.
String sval: If the token is a word, this filed contains the word that can be used in programming.
double nval: If the token is a word, this filed contains the number that can be used in
programming.

The following program, STDemo.java, reads the AllContent.txt file and prints the number of
numerical values, number of words and number of total characters that appear and the total value
of all the numbers.

File Name : AllContent.txt


hello 10 world 20.5

The above file contents are tokenized in the following program.

import java.io.*;
public class STDemo
{
public static void main(String args[]) throws IOException
{
FileReader freader = new FileReader("AllContent.txt");
StreamTokenizer st = new StreamTokenizer(freader);

double sum = 0;
int numWords = 0, numChars = 0;

while(st.nextToken() != st.TT_EOF)
{
if(st.ttype == StreamTokenizer.TT_NUMBER)
{
sum += st.nval;
}
else if(st.ttype == StreamTokenizer.TT_WORD)
{
numWords++;
numChars += st.sval.length();
}
}
System.out.println("Sum of total numbers in the file: " + sum);
System.out.println("Total words (does not include numbers) in the file: " + numWords);
System.out.println("No. of characters available in words: " + numChars);
}
}

output:

Sumf total numbers in the file: 30.5


Total words (does not include numbers) in the file: 2
No. of characters available in words: 10

Wrapper class in Java

Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into
primitive automatically. The automatic conversion of primitive into object is known as
autoboxing and vice-versa unboxing.

The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:

Primitive Type Wrapper Class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Wrapper class Example: Primitive to Wrapper

public class WrapperExample1


{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}
}
Output:

20 20 20

Wrapper class Example: Wrapper to Primitive

public class WrapperExample2


{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}
}
Output:

333

S-ar putea să vă placă și