Module 5
Module 5
Module V
Module V- Syllabus
• Working with the String and StringBuilder class, Character class,
Tokenizing strings, Regular Expressions, Files and Streams, Using NIO
classes, Sequential file handling, Object serialization, JFileChooser,
Introduction to threading, Introduction to Generics and lambda
expressions.
Java Regex(Regular Expression)
• The Java Regex or Regular Expression is an API to define a pattern for searching
or manipulating strings.
• It is widely used to define the constraint on strings such as password and email
validation.
• After learning Java regex tutorial, you will be able to test your regular expressions
by the Java Regex Tester Tool.
• Java Regex API provides 1 interface and 3 classes in java.util.regex package.
• The java.util.regex package provides following classes and interfaces for regular
expressions.
• MatchResult interface
• Matcher class
• Pattern class
• PatternSyntaxException class
Matcher class
1 boolean matches() test whether the regular expression matches the pattern.
2 boolean find() finds the next expression that matches the pattern.
3 boolean find(int start) finds the next expression that matches the pattern from the given
start number.
4 String group() returns the matched subsequence.
5 int start() returns the starting index of the matched subsequence.
6 int end() returns the ending index of the matched subsequence.
7 int groupCount() returns the total number of the matched subsequence.
Pattern class
It is the compiled version of a regular expression.
It is used to define a pattern for the regex engine.
1 static Pattern compile(String regex) compiles the given regex and returns the instance of
the Pattern.
2 Matcher matcher(CharSequence input) creates a matcher that matches the given input with
the pattern.
3 static boolean matches(String regex, It works as the combination of compile and matcher
CharSequence input) methods. It compiles the regular expression and
matches the given input with the pattern.
4 String[] split(CharSequence input) splits the given input string around matches of given
pattern.
5 String pattern() returns the regex pattern.
Example
import java.util.regex.*;
public class Main{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
• System.out.println(Pattern.matches("[amn]", "ammmna"));
//false (m and a comes more than once)
Regex Quantifiers
Regex Description
• System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n m
ay come zero or more times)
Regex Metacharacters
The regular expression metacharacters work as shortcodes.
Regex Description
• It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
• A thread in Java at any point of time exists in any one of the following
states.
• A thread lies only in one of the shown states at any instant:
• New
• Runnable
• Blocked
• Waiting
• Timed Waiting
• Terminated
Life cycle of a Thread
How to create thread
• Thread class provide constructors and methods to create and perform operations
on a thread.
• The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread.
• We are passing the object of your class that implements Runnable so that your
class run() method may execute.
Java Thread Example by extending Thread class
t1.start();
t2.start();
}
}
• Output
1
1
2
2
3
3
4
4
• The join() method
• It causes the currently running threads to stop executing until the
thread it joins with completes its task.
Example
t2.start();
t3.start();
}
}
• Output:1
• 2
• 3
• 4
• 5
• 1
• 1
• 2
• 2
• 3
• 3
• 4
• 4
• 5
• 5
Example:getName() and setName()
Name of t1:Thread-0
Name of t2:Thread-1
running...
After changing name of t1:New_Thread
running...
Priority of a Thread (Thread Priority):
• In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling).
}
}
• Output
running thread name is:Thread-0
running thread priority is:1
running thread name is:Thread-1
running thread priority is:10
Points to Remember
t1.run();
t2.run();
}
}
• Output
1
2
3
4
1
2
3
4
Streams and Files in Java
• It's called a stream because it is like a stream of water that continues to flow.
• OutputStream
• InputStream
• Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
• OutputStream class
• An output stream accepts output bytes and sends them to some sink.
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 IOException is used to write an array of byte to the current output
stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
• InputStream class
Method Description
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It returns
-1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes that can be read
from the current input stream.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Java FileOutputStream Class
• If you have to write primitive values into a file, use FileOutputStream class.
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
• Output
Success...
• It is used for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
Method Description
int available() It is used to return the estimated number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input
stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the
file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no
more reference to the file input stream.
Example
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
• Output
A
• To read all the characters
• int i=0;
• while((i=fin.read())!=-1){
• System.out.print((char)i);
Java FileWriter Class
Method Description
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("testout.txt");
fw.write("Welcome to java.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
• Output
Success...
Java FileReader Class
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
Example
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
• Output
Welcome to java
Serialization and Deserialization in Java
• Deserialization is the reverse process where the byte stream is used to recreate
the actual Java object in memory.
• It is used to “mark” java classes so that objects of these classes may get certain
capability.
SerialVersionUID
• The Serialization runtime associates a version number with each Serializable class
called a SerialVersionUID, which is used during Deserialization to verify that
sender and reciever of a serialized object have loaded classes for that object
which are compatible with respect to serialization.
• If the reciever has loaded a class for the object that has different UID than that of
corresponding sender’s class, the Deserialization will result in
an InvalidClassException.
Example
import java.io.*;
}
class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, "java");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Demo object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
object1 = (Demo)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized ");
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}}}
• Output
Object has been serialized
Object has been deserialized
a = 1
b = java
• Points to remember
• If a parent class has implemented Serializable interface then child class doesn’t need to
implement it but vice-versa is not true.
• Static data members and transient data members are not saved via Serialization
process.So, if you don’t want to save value of a non-static data member then make it
transient.