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

Java Unit 2 Fully

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

Java Unit 2 Fully

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

Unit – II

String Handling - I
[Link]
SAP / ICT / SOC
SASTRA
Unit - II
• Multithreaded Programming:
• Java Thread Model - The Main Thread - Creating a
Thread - Creating Multiple Threads - Thread Priorities
- Synchronization.

• I/O:
• I/O Basics - Reading Console Input - Writing Console
Output.

• String Handling:
• String - String Buffer - String Builder

10/6/2021 5:14 PM CSE 208 – Java Programming 2


• Strings.
• String Operations.

• StringBuffer.
• StringBuffer Operations.

• StringBuilder
• StringBuilder Operations

10/6/2021 5:14 PM CSE 208 – Java Programming 3


Strings

• Java string is a sequence of characters.

• They are objects of type String. char str[100];


– String
– StringBuffer
– StringBuilder

• Once a String object is created it cannot be changed.

• Strings are Immutable.

10/6/2021 5:14 PM CSE 208 – Java Programming 4


Strings

• To get changeable strings use the class called


StringBuffer.

• String and StringBuffer classes are declared final


• so there cannot be subclasses of these classes.

class demo extends String


{
}

10/6/2021 5:14 PM CSE 208 – Java Programming 5


Creating Strings
• The default constructor creates an empty string.
String s = new String();

char data[] = {'a', 'b', 'c'};


String str = new String(data);

• If data array in the above example is modified


– after the string object str is created,
– then str remains unchanged.

• Construct a string object by passing another string


object.
String str2 = new String(str);

10/6/2021 5:14 PM CSE 208 – Java Programming 6


Creating Strings
• String str=“Java”;

• String str=new String(“Java”);

• String a = "Java";
• String b = "Java";
• [Link](a == b); // true

• String c = new String("Java");


• String d = new String("Java");
• [Link](c == d); // False

10/6/2021 5:14 PM CSE 208 – Java Programming 7


Creating Strings
• These double quoted literal is known as String literal and the cache
which stored these String instances are known as String pool.
• In earlier version of Java,
– String pool is located in permgen area of heap,
– but in Java 1.7 updates its moved to main heap area.

• Earlier since it was in PermGen space,


– it was always a risk to create too many String object,
– because its a very limited space,
– default size 64 MB and used to store class metadata e.g. .class
files.
• Creating too many String literals can
cause [Link]: permgen space.

10/6/2021 5:14 PM CSE 208 – Java Programming 8


Difference between String literal and String object

Now because String pool is moved to a much larger memory space, it's
much more safe.

10/6/2021 5:14 PM CSE 208 – Java Programming 9


10/6/2021 5:14 PM CSE 208 – Java Programming 10
String Operations

• The length() method returns the length of the string.


Eg: [Link](“Hello”.length()); // prints 5

• The + operator is used to concatenate two or more


strings.

Eg: String myname = “Harry”


String str = “My name is” + myname+ “.”;
My name is Harry.

10/6/2021 5:14 PM CSE 208 – Java Programming 11


String Operations
• For string concatenation
• the Java compiler converts an operand to a String
• whenever the other operand of the + is a String object.

String s="six"+3+3; E:\slides\Java - 2021\Unit - II>java string


[Link](s); six33

String s="six"+(3+3); E:\slides\Java - 2021\Unit - II>java string


[Link](s); six6

10/6/2021 5:14 PM CSE 208 – Java Programming 12


Character Extraction
• Characters in a string can be extracted in a number of
ways.

• public char charAt(int index)


– Returns the character at the specified index.
– An index ranges from 0 to length() - 1.
– The first character of the sequence is at index 0, the
next at index 1, and so on, as for array indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”

10/6/2021 5:14 PM CSE 208 – Java Programming 13


Character Extraction
ch = “abc”.charAt(10);
ch = “abc”.charAt(-1);

E:\slides\Java - 2021\Unit - II>javac [Link]

E:\slides\Java - 2021\Unit - II>java string


Exception in thread "main" [Link]: String
index out of range: 10
at [Link](Unknown Source)
at [Link]([Link])

E:\slides\Java - 2021\Unit - II>javac [Link]


E:\slides\Java - 2021\Unit - II>java string
Exception in thread "main" [Link]: String
index out of range: -1
at [Link](Unknown Source)
at [Link]([Link])

10/6/2021 5:14 PM CSE 208 – Java Programming 14


Character Extraction
• getChars() - Copies characters from this string into the
destination character array.

public void getChars(int srcBegin,


int srcEnd,
char[] dst,
int dstBegin)

– srcBegin - index of the first character in the string to copy.


– srcEnd - index after the last character in the string to copy.
– dst - the destination array.
– dstBegin - the start offset in the destination array.

10/6/2021 5:14 PM CSE 208 – Java Programming 15


Character Extraction - Example
class string
{
public static void main(String args[])
{ E:\slides\Java - 2021\Unit - II>java string
String s1="SASTRA Deemed University";
SASTRA Deemed University
char c[]=new char[10]; 0 1 2345678
STRA D
[Link](s1);
[Link](2,8,c,0);
[Link](c);

}
}

10/6/2021 5:14 PM CSE 208 – Java Programming 16


Character Extraction - Example
class string
{
public static void main(String args[])
{
String s1="SASTRA Deemed University";

char c[]=new char[10];


[Link](s1);
[Link](2,8,c,11);
[Link](c);
E:\slides\Java - 2021\Unit - II>javac [Link]
}
E:\slides\Java - 2021\Unit - II>java string
}
SASTRA Deemed University
Exception in thread "main" [Link]
at [Link](Native Method)
at [Link](Unknown Source)
at [Link]([Link])

10/6/2021 5:14 PM CSE 208 – Java Programming 17


String Comparison

• equals() - Compares the invoking string to the specified object.


• The result is true if and only if the argument is not null and is a
String object that represents the same sequence of characters as
the invoking object.
public boolean equals(Object anObject)

• equalsIgnoreCase()- Compares this String to another String,


ignoring case considerations.
• Two strings are considered equal ignoring case if they are of the
same length, and corresponding characters in the two strings are
equal ignoring case.

public boolean equalsIgnoreCase(String anotherString)

10/6/2021 5:14 PM CSE 208 – Java Programming 18


String Comparison
• startsWith() – Tests if this string starts with the specified
prefix.

public boolean startsWith(String prefix)


“Figure”.startsWith(“Fig”); // true

• endsWith() - Tests if this string ends with the specified


suffix.

public boolean endsWith(String suffix)


“Figure”.endsWith(“re”); // true

10/6/2021 5:14 PM CSE 208 – Java Programming 19


String Comparison
• startsWith() -Tests if this string starts with the specified
prefix beginning at a specified index.
public boolean startsWith(String prefix,
int toffset)
prefix - the prefix.
toffset - where to begin looking in the
string.

“figure”.startsWith(“gure”, 2); // true

10/6/2021 5:14 PM CSE 208 – Java Programming 20


String Comparison

• compareTo() - Compares two strings lexicographically.


– The result is a negative integer if this String object
lexicographically precedes the argument string.
– The result is a positive integer if this String object
lexicographically follows the argument string.
– The result is zero if the strings are equal.
– compareTo returns 0 exactly when the equals(Object) method
would return true.

public int compareTo(String anotherString)


public int compareToIgnoreCase(String str)

10/6/2021 5:14 PM CSE 208 – Java Programming 21


String Comparison - Example
class string
{
public static void main(String args[])
{
String s1=new String("Abisheik");
String s2=new String("Bharath");
String s3=new String(s1);

int x=[Link](s2); E:\slides\Java - 2021\Unit - II>java string


int y=[Link](s1); -1
int z=[Link](s3); 1
0
[Link](x);
[Link](y);
[Link](z);
}
}

10/6/2021 5:14 PM CSE 208 – Java Programming 22


Searching Strings
 indexOf – Searches for the first occurrence of a character or
substring. Returns -1 if the character does not occur.

public int indexOf(int ch)- Returns the index within this


string of the first occurrence of the specified character.

public int indexOf(String str) - Returns the index within


this string of the first occurrence of the specified substring.

String str = “How was your day today?”;


[Link](‘w’); //2
[Link](“was”); //4

10/6/2021 5:14 PM CSE 208 – Java Programming 23


Searching Strings
public int indexOf(int ch, int fromIndex)
-Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.

public int indexOf(String str, int fromIndex)


-Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.

String str = “How was your day today?”;


[Link](‘w’,3); //4
[Link](“day”,17); //19

10/6/2021 5:14 PM CSE 208 – Java Programming 24


Searching Strings
lastIndexOf()
 Searches for the last occurrence of a character or substring.
 The methods are similar to indexOf().

String str = “How was your day today?”;


[Link](‘y’); //21
[Link]([Link]("day",21));//19
[Link]([Link]("day",18));//13

10/6/2021 5:14 PM CSE 208 – Java Programming 25


Modifying a String
substring
• Returns a new string that is a substring of this string.
• The substring begins with the character at the specified
index and extends to the end of this string.

• public String substring(int beginIndex)


Eg: "unhappy".substring(2) returns "happy"

• public String substring(int beginIndex,int endIndex)

Eg: "smiles".substring(1, 5) returns "mile“

10/6/2021 5:14 PM CSE 208 – Java Programming 26


Modifying a String
Concat
• Concatenates the specified string to the end of this
string.

• If the length of the argument string is 0, then this String


object is returned.

• Otherwise, a new String object is created, containing the


invoking string with the contents of the str appended to it.

public String concat(String str)


"to".concat("get").concat("her")
returns "together"

10/6/2021 5:14 PM CSE 208 – Java Programming 27


Modifying a String
• Replace
• Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

public String replace(char oldChar, char newChar)

"mesquite in your cellar".replace('e', 'o')

returns

"mosquito in your collar"

10/6/2021 5:14 PM CSE 208 – Java Programming 28


Modifying a String
• trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.

public String trim()

String s = “ Hi Mom! “.trim();


S = “Hi Mom!”

10/6/2021 5:14 PM CSE 208 – Java Programming 29


Modifying a String
• toLowerCase():
– Converts all of the characters in a String to lower case.
• toUpperCase():
– Converts all of the characters in this String to upper case.

public String toLowerCase()


public String toUpperCase()

Eg: “HELLO THERE”.toLowerCase();


“hello there”

E
n
d
10/6/2021 5:14 PM CSE 208 – Java Programming 30
• String Definition
• String Class Constructors
• String Operations
– Pattern Matching
– Searching
– Modification

10/6/2021 5:14 PM CSE 208 – Java Programming 31


 String Buffer
 String Builder

10/6/2021 5:14 PM CSE 208 – Java Programming 32


10/6/2021 5:14 PM CSE 208 – Java Programming 33
String Handling - II

[Link]
SAP / ICT / SOC
SASTRA
• StringBuffer.
• StringBuffer Operations.

• StringBuilder
• StringBuilder Operations

• String Tokenizer

10/8/2021 2:04 PM CSE 208 – Java Programming 2


Review Question - 1

class string
{
public static void main(String args[])
{
String s1=new String();
[Link](s1);
}
}

10/8/2021 2:04 PM CSE 208 – Java Programming 3


String Constructors - continued
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)

String(StringBuffer strBufObj)

String(StringBuilder strBuildObj)

class string
{
public static void main(String args[]) E:\slides\Java - 2021\Unit - II>java string
{ ABC
byte b[]={65,66,67};
String s=new String(b);
[Link](s);
}
}

10/8/2021 2:04 PM CSE 208 – Java Programming 4


region Matches()
• regionMatches( ) method
– compares a specific region inside a string with
another specific region in another string.

10/8/2021 2:04 PM CSE 208 – Java Programming 5


region Matches()
class string
{
public static void main(String args[])
{

boolean b= "SASTRA".regionMatches(1,"SASSAS",4,2);
[Link](b);

boolean c= "SASTRA".regionMatches(1,"SASTRA",4,2);
[Link](c);
}
E:\slides\Java - 2021\Unit - II>java string
} true
false

10/8/2021 2:04 PM CSE 208 – Java Programming 6


Data Conversion Using valueOf( )

The valueOf() method


 converts data from its internal format into a humanreadable
form.
It is a static method that is overloaded within String for all of Java’s
built-in types
valueOf( ) is also overloaded for type Object

 static String valueOf(double num)


 static String valueOf(long num)
 static String valueOf(Object ob)
 static String valueOf(char chars[ ])

valueOf( ) can be called when a string representation of some


other type of data is needed

10/8/2021 2:04 PM CSE 208 – Java Programming 7


Data Conversion Using valueOf()
class string
{
public static void main(String args[])
{
int x=10; E:\slides\Java - 2021\Unit - II>java string
double d=12.34; 10
12.34
true
String s=new String("10");

[Link]([Link](x));
[Link]([Link](d));

[Link]([Link]([Link](x)));

}
}
10/8/2021 2:04 PM CSE 208 – Java Programming 8
Joining Strings
JDK 8 added a new method to String called join().
It is used to concatenate two or more strings, separating each
string with a delimiter, such as a space or a comma.
static String join(CharSequence delim, CharSequence . . . strs)
class string
{
public static void main(String args[])
{
String result=[Link](" ","SASTRA","Deemed","University");
[Link](result);
}
}

E:\slides\Java - 2021\Unit - II>java string


SASTRA Deemed University

10/8/2021 2:04 PM CSE 208 – Java Programming 9


10/8/2021 2:04 PM CSE 208 – Java Programming 10
StringBuffer
• A StringBuffer is like a String, but can be modified.

• The length and content of the StringBuffer sequence can be


changed through certain method calls.

• StringBuffer may have characters and substrings inserted in the


middle or appended to the end.

• StringBuffer defines four constructors:


– StringBuffer()
– StringBuffer(int size)
– StringBuffer(String str)
– StringBuffer(CharSequence chars)

10/8/2021 2:04 PM CSE 208 – Java Programming 11


StringBuffer Operations - append

• The principal operations on a StringBuffer are the


append and insert methods, which are overloaded so as
to accept data of any type.

Here are few append methods:

 StringBuffer append(String str)


 StringBuffer append(int num)

• The append method always adds these characters at the


end of the buffer.

10/8/2021 2:04 PM CSE 208 – Java Programming 12


StringBuffer Operations - insert

• The insert method adds the characters at a specified


point.

Here are few insert methods:


 StringBuffer insert(int index, String str)
 StringBuffer insert(int index, char ch)

• Index specifies at which point the string will be inserted


into the invoking StringBuffer object.

10/8/2021 2:04 PM CSE 208 – Java Programming 13


StringBuffer – Example 1

class string
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("SASTRA");
[Link](sb);

[Link]("University");
[Link](sb); E:\slides\Java - 2021\Unit - II>java string
SASTRA
[Link](6,"Deemed"); SASTRAUniversity
[Link](sb); SASTRADeemedUniversity

}
}

10/8/2021 2:04 PM CSE 208 – Java Programming 14


StringBuffer Operations - delete
• delete() / deleteCharAt()
• Removes the characters in a substring of this StringBuffer.

• The substring begins at the specified start and extends


to the character at index end - 1 or to the end of the
StringBuffer if no such character exists.

• If start is equal to end, no changes are made.

 StringBuffer delete(int start, int end)


 StringBuffer deleteCharAt(int loc)

10/8/2021 2:04 PM CSE 208 – Java Programming 15


StringBuffer Operations

• replace()

• Replaces the characters in a substring of this


StringBuffer with characters in the specified String.

 public StringBuffer replace(int start, int end,


String str)

10/8/2021 2:04 PM CSE 208 – Java Programming 16


StringBuffer Operations

• reverse()

• The character sequence contained in this string buffer is


replaced by the reverse of the sequence.

 public StringBuffer reverse()

10/8/2021 2:04 PM CSE 208 – Java Programming 17


StringBuffer – Example 2
class string
{
public static void main(String args[])
{ E:\slides\Java - 2021\Unit - II>java string
[Link](sb);
SASTRADeemedUniversity
[Link](0);
[Link](sb); ASTRADeemedUniversity

[Link](0,5); DeemedUniversity
[Link](sb);
ytisrevinUdemeeD
[Link]([Link]());
}
}

10/8/2021 2:04 PM CSE 208 – Java Programming 18


StringBuffer Operations
• length()
• Returns the length of this string buffer.
public int length()
• capacity()
• Returns the current capacity of the String buffer.
• The capacity is the amount of storage available for newly
inserted characters.
public int capacity()
• setLength()
• Sets the length of the StringBuffer.
public void setLength(int newLength)

10/8/2021 2:04 PM CSE 208 – Java Programming 19


StringBuffer – Example 3
StringBuffer sb = new StringBuffer(“Hello”);
[Link](); // 5
[Link](); // 21 (16 characters room is
added if no size is specified)
[Link](1); // e
[Link](1,’i’); // Hillo
[Link](2); // Hi
[Link](“l”).append(“l”); // Hill
[Link](0, “Big “); // Big Hill
[Link](3, 11, “”); // Big
[Link](); // gib
E
n
10/8/2021 2:04 PM CSE 208 – Java Programming 20
d
10/8/2021 2:04 PM CSE 208 – Java Programming 21
Introduction

• StringBuilder is identical to StringBuffer

– except for one important difference


– it is not synchronized,
– which means it is not thread safe.

10/8/2021 2:04 PM CSE 208 – Java Programming 22


Introduction
• In other words,
– if multiple threads are accessing a StringBuilder
instance at the sametime,
– its integrity cannot be guaranteed.

• However,
– for a single-thread program (most commonly),
– doing away with the overhead of synchronization
makes the StringBuilder faster.

10/8/2021 2:04 PM CSE 208 – Java Programming 23


StringBuilder Constructors
StringBuilder( )
Creates an empty string builder with a capacity of 16 (16 empty
elements).

StringBuilder(int size)
Creates an empty string builder with the specified initial capacity.

StringBuilder (String str )


Creates a string builder whose value is initialized by the specified
string, plus an extra 16 empty elements trailing the string.

StringBuilder(CharSequence cs)
Constructs a string builder containing the same characters as the
specified CharSequence, plus an extra 16 empty elements trailing
the CharSequence.

10/8/2021 2:04 PM CSE 208 – Java Programming 24


StringBuilder – Example 1
class string
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("SASTRA");
[Link](sb);
E:\slides\Java - 2021\Unit - II>java string
[Link]([Link]()); SASTRA
22
[Link](3); SAS
[Link](sb);

}
}

E
n
10/8/2021 2:04 PM CSE 208 – Java Programming 25
d
String Tokenizer
class

10/8/2021 2:04 PM CSE 208 – Java Programming 26


StringTokenizer class
• The processing of text often consists of parsing a
formatted input string.

• Parsing is the division of text into a set of discrete parts,


or tokens, which in a certain sequence can convey a
semantic meaning.

• The StringTokenizer class provides the first step in this


parsing process, often called the lexer (lexical analyzer)
or scanner.

10/8/2021 2:04 PM CSE 208 – Java Programming 27


StringTokenizer class
• To use StringTokenizer,
– you specify an input string and
– a string that contains delimiters.

• Delimiters are characters that separate tokens.

• Each character in the delimiters string is considered a valid


delimiter—for example, ",;:" sets the delimiters to a comma,
semicolon, and colon.

• The default set of delimiters consists of the whitespace characters:


space, tab, newline,and carriage return.

10/8/2021 2:04 PM CSE 208 – Java Programming 28


StringTokenizer Constructors
StringTokenizer(String, String)
Constructs a StringTokenizer on the specified String,
using the specified delimiter set.

StringTokenizer(String)
Constructs a StringTokenizer on the specified String,
using the default delimiter set (which is " \t\n\r").

10/8/2021 2:04 PM CSE 208 – Java Programming 29


Methods
[Link]()
Returns the next number of tokens in the String using
the current deliminter set.

b. hasMoreTokens()
Returns true if more tokens exist.

c. nextToken()
Returns the next token of the String.

10/8/2021 2:04 PM CSE 208 – Java Programming 30


Example usage
String s = "this is a test";
StringTokenizer st = new StringTokenizer(s);
while ([Link]()) {
println([Link]());
}

Prints the following on the console:


this
is
a
test

10/8/2021 2:04 PM CSE 208 – Java Programming 31


 Additional constructors in String.
 Other methods – String

 StringBuffer – Constructors / Methods

 StringBuilder – Constructors

 Use of String Tokenizer class

10/8/2021 2:04 PM CSE 208 – Java Programming 32


Files

10/8/2021 2:04 PM CSE 208 – Java Programming 33


10/8/2021 2:04 PM CSE 208 – Java Programming 34
Java’s basic
I/O System
[Link]
SAP / ICT / SOC
SASTRA
 Need for File
 Data Hierarchy
 Streams
 Predefined Streams
 Reading Console Input
 Writing Console Output
 Reading and Writing Files
 File Class

10/9/2021 9:05:00 AM CSE208 - Java Programming 2


C - Input/Output Recap

 FILE* fp;
 fp = fopen(“[Link]”, “rw”);

 fscanf(fp, ……);
 frpintf(fp, …..);

 fread(………, fp);
 fwrite(……….., fp);

10/9/2021 9:05:00 AM CSE208 - Java Programming 3


I/O and Data Movement

4
Why do we need to store data in file?

10/9/2021 9:14:22 AM CSE208 - Java Programming 5


Need for File

 Storage of data in variables and arrays is temporary

 Files
 used for long-term retention of large amounts of data
 even after the programs that created the data
terminate

 Persistent data
 exists beyond the duration of program execution

 Files stored on secondary storage devices

10/9/2021 9:05:00 AM CSE208 - Java Programming 6


Data Hierarchy
 Computers process all data items as combinations of
zeros and ones

 Bit – smallest data item on a computer, can have values


0 or 1

 Byte – 8 bits

 Characters – larger data item


 Consists of decimal digits, letters and special symbols
 Character set – set of all characters used to write
programs and represent data items
Unicode – characters composed of two bytes
ASCII

10/9/2021 9:05:00 AM CSE208 - Java Programming 7


Data Hierarchy

• Fields – a group of characters or bytes that conveys


meaning

• Record – a group of related fields

• File – a group of related records

10/9/2021 9:05:00 AM CSE208 - Java Programming 8


Data Hierarchy
 Data can be arranged in a hierarchy.

A database is a
collection of files.

A byte is a
collection of bits.

10/9/2021 9:05:00 AM CSE208 - Java Programming 9


Streams and Files
Java performs i/o – streams
stream - abstraction - produces/consumes information
logical entity
stream - linked - physical device - same manner -
file/keyboard/socket

[Link]
[Link]

10/9/2021 9:05:00 AM CSE208 - Java Programming 10


Reading Data

To bring in information, a program opens a stream on


an information source (a file, memory, a socket) and
reads the information sequentially, as shown in the
following figure.

10/9/2021 9:05:00 AM CSE208 - Java Programming 11


Writing Data

A program can send information to an external


destination by opening a stream to a destination
and writing the information out sequentially, as
shown in the following figure.

10/9/2021 9:05:00 AM CSE208 - Java Programming 12


Streams - Classification

Byte Streams Character streams


(JDK 1.1)
when reading or writing input and output of
binary data characters
Operated on 8 bit (1 byte) Operates on 16-bit (2 byte)
data. unicode characters.

Input stream/Output stream Reader/ Writer

10/9/2021 9:05:00 AM CSE208 - Java Programming 13


Classification of Java Stream Classes

Byte Stream Character Stream


classes classes

10/9/2021 9:05:00 AM CSE208 - Java Programming 14


Byte Input Streams
InputStream
ObjectInputStream
SequenceInputStream

ByteArrayInputStream
PipedInputStream

FilterInputStream

PushbackInputStream
BufferedInputStream
DataInputStream

10/9/2021 9:05:00 AM CSE208 - Java Programming 15


Byte Input Streams - operations

public abstract int read() Reads a byte and returns


as a integer 0-255
public long skip(long count) Skips count bytes.

public int available() Returns the number of


bytes that can be read.
public void close() Closes stream

16
The Predefined Streams
• All Java programs automatically import the [Link]
package.
• This package defines a class called System,
– which encapsulates several aspects of the run-time
environment.
• For example,
– using some of its methods,
– you can obtain the current time
– the settings of various properties associated with the
system.
• System also contains three predefined stream
variables: in, out, and err.

10/9/2021 9:05:00 AM CSE208 - Java Programming 17


The Predefined Streams
• These fields are declared as public, static, and final
within System.
• They can be used by any other part of your program and
without reference to a specific System object.

• [Link] refers to the standard output stream.


– By default, this is the console.
• [Link] refers to standard input,
– keyboard by default.
• [Link] refers to the standard error stream,
– console by default.

10/9/2021 9:05:00 AM CSE208 - Java Programming 18


The Predefined Streams

• [Link]
– is an object of type InputStream
• [Link] and [Link]
– are objects of type PrintStream

10/9/2021 9:05:00 AM CSE208 - Java Programming 19


Reading Console Input
import [Link].*;
int read( ) throws IOException
class consoleread
{
public static void main(String args[]) throws Exception
{
char c;
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter Characters, q to quit");
do
{ E:\slides\Java - 2021\Unit - II>java consoleread
Enter Characters, q to quit
c=(char) [Link](); sastraq
[Link](c); s
}while(c!='q'); a
s
} t
} r
a
q

10/9/2021 9:05:00 AM CSE208 - Java Programming 20


Reading Strings
import [Link].*; String readLine( ) throws IOException

class readingstrings
{
public static void main(String args[]) throws Exception
{
String str;
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter a String ");
str=[Link](); E:\slides\Java - 2021\Unit - II>java readingstrings
[Link](str); Enter a String
SASTRA
}
SASTRA
}

E:\slides\Java - 2021\Unit - II>javac [Link]


Note: [Link] uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

10/9/2021 9:05:00 AM CSE208 - Java Programming 21


Writing Console Output

import [Link].*;
void write(int byteval)
class writedemo
{
public static void main(String args[]) throws Exception
{
int ch;
ch='a';
E:\slides\Java - 2021\Unit - II>java writedemo
[Link](ch);
a
[Link]('\n');
}
E:\slides\Java - 2021\Unit - II>
}

10/9/2021 9:05:00 AM CSE208 - Java Programming 22


Reading and Writing Files
import [Link].*;

class filedemo
{
public static void main(String args[]) throws Exception
{
FileInputStream f=new FileInputStream("[Link]");
int size=[Link](); E:\slides\Java - 2020\Unit - II>java filedemo
import [Link].*;
for(int i=0;i<size;i++) class filedemo
{ {
public static void main(String args[]) throws Exception
[Link]((char)[Link]()); {
} FileInputStream f=new FileInputStream("[Link]");
int size=[Link]();
}
} for(int i=0;i<size;i++)
{
[Link]((char)[Link]());
}

}
}

10/9/2021 9:05:00 AM CSE208 - Java Programming 23


Reading and Writing Files
import [Link].*;

class filedemo1
{
public static void main(String args[]) throws Exception
{
FileInputStream fin=new FileInputStream("[Link]");
FileOutputStream fout=new FileOutputStream("[Link]");

int i;
do
{
i=[Link]();

if(i!=-1)
[Link](i);

}while(i!=-1);
}
}
10/9/2021 9:05:00 AM CSE208 - Java Programming 24
10/9/2021 9:05:01 AM CSE208 - Java Programming 25
File class
 Does not operate on streams describes the properties of
a file

File(String directorypath)
File(String directorypath,String filename)

 File Class is not symmetrical.

 Class File useful for retrieving information about files and


directories from disk

 Objects of class File do not open files or provide any file-


processing capabilities

10/9/2021 9:05:01 AM CSE208 - Java Programming 26


File class
[Link]
import [Link].*;

class fdemo
{
public static void main(String args[]) E:\slides\Java - 2020\Unit - II>java fdemo
{ [Link]
File f=new File("[Link]"); true
[Link]([Link]()); true
[Link]([Link]()); true
[Link]([Link]()); false
[Link]([Link]()); true
[Link]([Link]()); False
[Link]([Link]()); 434
[Link]([Link]());
[Link]([Link]());
}
}

10/9/2021 9:05:01 AM CSE208 - Java Programming 27


We have discussed
 Streams
 Predefined Streams
 Reading Console Input
 Writing Console Output
 Reading and Writing Files
 File Class

10/9/2021 9:05:01 AM CSE208 - Java Programming 28


Multithreading
10/9/2021 9:05:01 AM CSE208 - Java Programming 30
Multithreading - I

[Link]
SAP / ICT / SOC
SASTRA
 Introduction
 Multitasking and Multithreading
 Thread Applications
 Defining Threads

10/12/2021 2:10:19 PM CSE 208 – Java Programming 2


Acknowledgement

 Prof. Rajkumar Buyya


 Cloud Computing and Distributed Systems (CLOUDS) Laboratory
 Dept. of Computer Science and Software Engineering
 University of Melbourne, Australia
 Slides – (8 to 15)

10/12/2021 2:10:19 PM CSE 208 – Java Programming 3


 Why do we need threads?

10/12/2021 2:10:19 PM CSE 208 – Java Programming 4


Why do we need threads?

 To enhance parallel processing


 To increase response to the user
 To utilize the idle time of the CPU
 Prioritize your work depending on priority

10/12/2021 2:10:19 PM CSE 208 – Java Programming 5


Example

 Consider a simple web server


 The web server listens for request and serves it
 If the web server was not multithreaded,
 the requests processing would be in a queue
 thus increasing the response time and also might hang the
server if there was a bad request.
 By implementing in a multithreaded environment
 the web server can serve multiple request simultaneously
thus improving response time

10/12/2021 2:10:20 PM CSE 208 – Java Programming 6


Multithreaded Server: For Serving
Multiple Clients Concurrently

Client 1 Process Server Process

Server
Threads
 Internet

Client 2 Process

10/12/2021 2:10:20 PM CSE 208 – Java Programming 7


Web/Internet Applications:
Serving Many Users Simultaneously

PC client

Internet
Server
Local Area Network

PDA

10/12/2021 2:10:20 PM CSE 208 – Java Programming 8


10/12/2021 2:10:20 PM CSE 208 – Java Programming 9
Introduction
 Multi-tasking (as carried out by an operating system) and
Multi-threading (as carried out by a single application)

 Multi-tasking refers to an operating system running several


processes concurrently
 Each process has its own completely independent data
 Multi-tasking is difficult to incorporate in application
programs requiring system programming primitives

 A thread is different from a process in that threads share the


same data
 Switching between threads involves much less overhead
than switching between programs
 Sharing data can lead to programming complications (for
example in reading/writing databases)

10/12/2021 2:10:20 PM CSE 208 – Java Programming 10


A single threaded program
class XYZ
class ABC
{
{
….
….
begin
public static void main(..)
public static void main(..)
{
{
… body

..
..
}
}
} end }

10/12/2021 2:10:20 PM CSE 208 – Java Programming 11


A Multithreaded Program

Main Thread

start
start start

Thread A Thread B Thread C

Threads may switch or exchange data/results

10/12/2021 2:10:20 PM CSE 208 – Java Programming 12


Single and Multithreaded Processes

Threads are light-weight processes within a process

Single-threaded Process Multiplethreaded Process


Threads of
Execution

Single instruction stream Common Multiple instruction stream


Address Space

10/12/2021 2:10:20 PM CSE 208 – Java Programming 13


Multithreading - Multiprocessors

Process Parallelism

CPU
P1

P2 CPU

P3 CPU

time

No of execution processes <= the number of CPUs

10/12/2021 2:10:20 PM CSE 208 – Java Programming 14


Multithreading on Uni-processor
Concurrency Vs Parallelism

 Process Concurrency

P1

P2 CPU

P3

time

Number of Simultaneous execution units > number of CPUs

10/12/2021 2:10:20 PM CSE 208 – Java Programming 15


Thread - Definition
 Java provides built-in support for multithreaded programming.
 A multithreaded program contains two or more parts that can
run concurrently.
 Each part of such a program is called a thread, and each
thread defines a separate path of execution.
 In a thread-based multitasking environment, the thread is the
smallest unit of dispatchable code.
 This means that a single program can perform two or more
tasks simultaneously.
 For instance, a text editor can format text at the same time
that it is printing, as long as these two actions are being
performed by two separate threads.

10/12/2021 2:10:20 PM CSE 208 – Java Programming 16


Thread - Definition
 Multitasking threads require less overhead than multitasking
processes.
 Processes are heavyweight tasks that require their own
separate address spaces.
 Interprocess communication is expensive and limited.
 Context switching from one process to another is also
costly.
 Threads, on the other hand, are lighter weight.
 They share the same address space and cooperatively
share the same heavyweight process.
 Interthread communication is inexpensive, and context
switching from one thread to the next is lower in cost.

10/12/2021 2:10:20 PM CSE 208 – Java Programming 17


Context Switch
OS – Silberschatz and Galvin

10/12/2021 2:10:20 PM CSE 208 – Java Programming 18


Thread – Creation 1
 Create a class that extends the Thread class
class MyThread extends Thread
Thread {
public void run()
{
MyThread [Link](" this thread is running ... ");
}
}

class ThreadEx1
{
public static void main(String [] args )
{
MyThread t = new MyThread();
[Link]();
}
}
10/12/2021 2:10:20 PM CSE 208 – Java Programming 19
Thread – Creation 2
 Create a class that implements the Runnable interface

class MyThread implements Runnable {


Runnable
public void run() {
[Link](" this thread is running ... ");
MyClass }
}

class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
[Link]();
}
}
10/12/2021 2:10:20 PM CSE 208 – Java Programming 20
Example - 1
class one extends Thread class two extends Thread
{ {
public void run() public void run()
{ {
for(int i=1;i<=5;i++) for(int j=1;j<=5;j++)
{ {
[Link]("From one:--->"+i); [Link]("From two:--->"+j);
} }
[Link]("Exit From one"); [Link]("Exit From two");
} }
} }

10/12/2021 2:10:20 PM CSE 208 – Java Programming 21


Example - 1

class threaddemo
{
public static void main(String args[])
{
one t1=new one();
two t2=new two();

[Link]();
[Link]();

[Link]("main thread exiting");


}
}

10/12/2021 2:10:20 PM CSE 208 – Java Programming 22


Output- First Run
E:\slides\Java - 2021\Unit - II>java threaddemo
main thread exiting
From two:--->1
From one:--->1
From one:--->2
From one:--->3
From one:--->4
From one:--->5
Exit From one
From two:--->2
From two:--->3
From two:--->4
From two:--->5
Exit From two

10/12/2021 2:10:20 PM CSE 208 – Java Programming 23


Output- Second Run
E:\slides\Java - 2021\Unit - II>java threaddemo
From one:--->1
From one:--->2
From one:--->3
From one:--->4
From one:--->5
main thread exiting
Exit From one
From two:--->1
From two:--->2
From two:--->3
From two:--->4
From two:--->5
Exit From two

10/12/2021 2:10:20 PM CSE 208 – Java Programming 24


 We have discussed :
 Need for Multithreading
 Multitasking vs Multithreading
 Options for creating a thread

10/12/2021 2:10:20 PM CSE 208 – Java Programming 25


 Life Cycle of Thread
 Thread Methods

10/12/2021 2:10:21 PM CSE 208 – Java Programming 26


Multithreading - II

[Link]
SAP / ICT / SOC
SASTRA
 Round Robin Algorithm
 Life Cycle of Thread
 Thread Methods
 Thread Priorities
 Using isAlive() and join()

10/13/2021 7:08:03 PM CSE 208 – Java Programming 2


Acknowledgement
 Prof. Rajkumar Buyya
 Cloud Computing and Distributed Systems (CLOUDS) Laboratory
 Dept. of Computer Science and Software Engineering
 University of Melbourne, Australia
 Slide -6

10/13/2021 7:08:03 PM CSE 208 – Java Programming 3


Basic Scheme
 Two threads with the same priority are competing for CPU
cycles, the situation is a bit complicated.
 operating systems,
 threads of equal priority are time-sliced automatically in
round-robin fashion.
 For other types of operating systems,
 threads of equal priority must voluntarily yield control to
their peers.
 If they don’t, the other threads will not run.

10/13/2021 7:08:03 PM CSE 208 – Java Programming 4


Basic Scheme
 A thread can voluntarily relinquish control.
 This occurs when explicitly yielding, sleeping, or when
blocked.
 In this scenario, all other threads are examined, and the
highest-priority thread that is ready to run is given the CPU.
 A thread can be preempted by a higher-priority thread.
 In this case, a lower-priority thread that does not yield the
processor is simply preempted—no matter what it is
doing—by a higher-priority thread.
 Basically, as soon as a higher-priority thread wants to run, it
does.
 This is called preemptive multitasking.

10/13/2021 7:08:03 PM CSE 208 – Java Programming 5


Life Cycle of Thread
new
start()
I/O completed
ready
Time expired/
resume()
notify() interrupted

sleeping blocked
waiting
dispatch
sleep()
wait() suspend()
running Block on I/O
completion

stop() dead

10/13/2021 7:08:03 PM CSE 208 – Java Programming 6


Thread Methods
 static void sleep(long milliseconds) throws InterruptedException
 static void sleep(long milliseconds, int nanoseconds) throws
InterruptedException

 public void yield()


[Link]
 public void start()
 public void stop()

 final void setName(String threadName)


 final String getName()

10/13/2021 7:08:04 PM CSE 208 – Java Programming 7


 We have discussed :
 RR algorithm
 Thread Methods

10/13/2021 7:08:04 PM CSE 208 – Java Programming 8


 Thread Priorities
 Using isAlive() and join()

10/13/2021 7:08:04 PM CSE 208 – Java Programming 9


Multithreading - III

[Link]
SAP / ICT / SOC
SASTRA
 Thread Priorities
 Using isAlive() and join()

10/15/2021 1:50:00 PM CSE 208 – Java Programming 2


Thread Priorities
 Java assigns to each thread a priority
 determines how that thread should be treated with respect
to the others.
 Thread priorities are integers that specify the relative priority of
one thread to another.
 As an absolute value, a priority is meaningless;
 a higher-priority thread doesn’t run any faster than a
lowerpriority thread if it is the only thread running.
 Instead, a thread’s priority is used to decide when to switch
from one running thread to the next.

10/15/2021 1:50:00 PM CSE 208 – Java Programming 3


Thread Priorities

 final void setPriority(int level)


 final int getPriority( )

[Link]
 values are 1 and 10

 MIN_PRIORITY - 1
 NORM_PRIORITY – 5 (Default)
 MAX_PRIORITY - 10

10/15/2021 1:50:00 PM CSE 208 – Java Programming 4


Using isAlive() and join()

¥ final boolean isAlive( )


¥ final void join( ) throws InterruptedException

[Link]

10/15/2021 1:50:00 PM CSE 208 – Java Programming 5


The Main Thread
 When a Java program starts up
 one thread begins running immediately.
 This is usually called the main thread of your program
 it is the one that is executed when your program begins.
 The main thread is important for two reasons:
 It is the thread from which other “child” threads will be
spawned.
 Often, it must be the last thread to finish execution because
it performs various shutdown actions.

10/15/2021 1:50:00 PM CSE 208 – Java Programming 6


The Main Thread
 Although the main thread is created automatically
 when your program is started
 it can be controlled through a Thread object.
 obtain a reference to it
Current Thread
 by calling the method currentThread()
 which is a public static member of Thread.
 Its general form is shown here:

static Thread currentThread( )

10/15/2021 1:50:00 PM CSE 208 – Java Programming 7


The Main Thread

E:\slides\Java - 2021\Unit - II>java currentthread


RUNNABLE

current thread:Thread[main,5,main]

After Name Change:Thread[ICT,5,main]

After Priority Change:Thread[ICT,10,main]

10/15/2021 1:50:00 PM CSE 208 – Java Programming 8


 We have discussed :
 Thread Priorities
 Using isAlive() and join()

10/15/2021 1:50:00 PM CSE 208 – Java Programming 9


 Synchronization

10/15/2021 1:50:00 PM CSE 208 – Java Programming 10


Multithreading - IV

[Link]
SAP / ICT / SOC
SASTRA
 Limitations of Multithreading
 Need for Synchronization
 Race Condition
 Producer-Consumer Problem

10/16/2021 10:36:02 AM CSE 208 – Java Programming 2


Limitations of Multithreading

 Multiple Threads namely p1,p2 and p3


 Concurrent execution – Data Inconsistency
 Sharable data – (x)

 Solution:
 Need to Synchronize the action between the
threads

10/16/2021 10:36:02 AM CSE 208 – Java Programming 3


Non Shared Data

Two Independent Threads


No need to Synchronize.

Thread 1: Thread 2:
int x=5; int y=5;
x=x+1; y=y-1;
[Link](x); [Link](y);

6 4

10/16/2021 10:36:02 AM CSE 208 – Java Programming 4


Cooperative Synchronized Threads

X=5
Thread 1:
Read x;
x=x+1;
Write x;

Thread 2:
Thread 1:6 Thread 2:4 Read x;
Thread 2:5 Thread 1:5 x=x-1;
Write x;
Final value of x=5

10/16/2021 10:36:02 AM CSE 208 – Java Programming 5


Producer / Consumer problem

Printer

Computer

10/16/2021 10:36:02 AM CSE 208 – Java Programming 6


Bounded Buffer
¥ Both routines are correct separately
¥ May not function correctly when executed concurrently
¥ Counter (x) = 5
¥ Producer ( Thread 1) – counter=counter+1
¥ Consumer (Thread 2) - counter=counter-1
¥ The value of counter is 4,6
¥ Correct value is 5 – executed separately

10/16/2021 10:36:02 AM CSE 208 – Java Programming 7


Bounded Buffer

 counter = counter + 1;
counter = counter - 1;

must be performed atomically.

 Atomic operation means an operation that completes in its


entirety without interruption.

10/16/2021 10:36:02 AM CSE 208 – Java Programming 8


Bounded Buffer
¥ The statement “counter=counter+1” may be implemented in
machine language as:

register1 = counter
register1 = register1 + 1
counter = register1

¥ The statement “counter=counter-1” may be implemented as:

register2 = counter
register2 = register2 – 1
counter = register2

¥ Register1,register2 are local CPU registers

10/16/2021 10:36:02 AM CSE 208 – Java Programming 9


Bounded Buffer
¥ If both the producer and consumer attempt to update the buffer
concurrently, the assembly language statements may get
interleaved.

¥ Interleaving depends upon how the producer and consumer


processes are scheduled.

Multiple
threads
sharing a
single CPU

10/16/2021 10:36:02 AM CSE 208 – Java Programming 10


Bounded Buffer
¥ Assume counter is initially 5. One interleaving of statements is:

T0:producer: register1 = counter (register1 = 5)


T1:producer: register1 = register1 + 1 (register1 = 6)

T2:consumer: register2 = counter (register2 = 5)


T3:consumer: register2 = register2 – 1 (register2 = 4)

T4:producer: counter = register1 (counter = 6)


T5:consumer: counter = register2 (counter = 4)

¥ The value of count may be either 4 or 6, where the correct


result should be 5.

10/16/2021 10:36:02 AM CSE 208 – Java Programming 11


Race Condition
 Race condition:
 The situation where several processes access – and
manipulate shared data concurrently.
 The final value of the shared data depends upon which
process finishes last.

 To prevent race conditions,


 concurrent processes must be synchronized.

10/16/2021 10:36:02 AM CSE 208 – Java Programming 12


 We have discussed :
 Need for Synchronization
 Producer-Consumer Problem
 Race Condition

10/16/2021 10:36:02 AM CSE 208 – Java Programming 13


 Interthread Communication

10/16/2021 10:36:02 AM CSE 208 – Java Programming 14


Multithreading - V

[Link]
SAP / ICT / SOC
SASTRA
 Synchronized Method
 Synchronized Block
 Interthread Communication

10/19/2021 2:03:57 PM CSE 208 – Java Programming 2


Synchronization

 When two or more threads need access to a shared resource


 they need some way to ensure that the resource will be used
by only one thread at a time.

 The process by which this is achieved is called synchronization.

 Key to synchronization is the concept of the monitor.

 A monitor is an object that is used as a mutually exclusive lock.

10/19/2021 2:03:57 PM CSE 208 – Java Programming 3


Monitor

10/19/2021 2:03:57 PM CSE 208 – Java Programming 4


Synchronization

 Only one thread can own a monitor at a given time.


 When a thread acquires a lock, it is said to have entered the
monitor.
 All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor.
 These other threads are said to be waiting for the monitor.
 A thread that owns a monitor can reenter the same monitor if it
so desires.

10/19/2021 2:03:57 PM CSE 208 – Java Programming 5


Synchronized Method

 To synchronize your code


 use the synchronized keyword
synchronized void show()
{
}

10/19/2021 2:03:57 PM CSE 208 – Java Programming 6


Interthread Communication
¥ wait( ) tells the calling thread to give up the monitor and go
to sleep until some other thread enters the same monitor and
calls notify( ) or notifyAll( ).
¥ notify( ) wakes up a thread that called wait( ) on the same
object.
¥ notifyAll( ) wakes up all the threads that called wait( ) on
the same object. One of the threads will be granted access.

¥ final void wait( ) throws InterruptedException


¥ final void notify( )
Producer/Consumer Problem
¥ final void notify All( )

10/19/2021 2:03:57 PM CSE 208 – Java Programming 7


Synchronized Block

 Suppose you have multiple lines of code in your method


 But you want to synchronize only few 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.

synchronized (object reference expression) Without Synchronized Block


{
//code block
} With Synchronized Block

10/19/2021 2:03:57 PM CSE 208 – Java Programming 8


Suspending and Resuming Threads

public void suspend():


is used to suspend the thread(depricated).
public void resume():
 is used to resume the suspended thread(depricated).

Program

10/19/2021 2:03:57 PM CSE 208 – Java Programming 9


 We have discussed :
 Synchronized Method
 Synchronized Block
 Interthread Communication
 Suspend and Resume Methods

10/19/2021 2:03:57 PM CSE 208 – Java Programming 10


 Unit III - Collections

10/19/2021 2:03:57 PM CSE 208 – Java Programming 11

You might also like