Unit - 3 More Features of The Java Platform
Unit - 3 More Features of The Java Platform
Java Platform
• Exception handling
• Input-output and file handling
• The collections framework and handling classes
P
in it
PP
• Introduction to the java.util package
• Multithreading
• Introduction to network programming
• Introduction to lambda expressions and
serialization
Exception
• Exception handling is a mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
P
• When an exceptional condition arises, an object representing that
PP
exception is created and thrown in the method that caused the error.
• That method may choose to handle the exception itself, or pass it on.
P
PP
Hierarchy of Exception Classes
• The java.lang.Throwable class is the root class of Java
Exception hierarchy
P
PP
Hierarchy of Exception Classes
Types of Java Exceptions
Two types of exceptions: Checked & Unchecked Exception
Difference between Checked and Unchecked Exceptions
1) Checked Exception
• Checked exceptions are checked at compile-time.
• The classes which inherit Throwable class except RuntimeException
and Error are known as checked exceptions
P
• e.g. IOException
SQLException
PP
ClassNotFoundException etc.
2) Unchecked Exception
• Unchecked exceptions are checked at runtime.
• The classes which inherit RuntimeException or inherit Error are
known as unchecked exceptions
• e.g. ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
StackoverflowError
VirtualMachineError etc.
Common Scenarios of Java Exceptions
int a = 50 / 0; // ArithmeticException
P
2. If we have a null value in any variable, performing any operation
on the variable throws a NullPointerException.
PP
String s = null;
System.out.println( s.length() ); // NullPointerException
Common Scenarios of Java Exceptions
3.The wrong formatting of any value may occur
NumberFormatException. Suppose I have a string variable that
has characters, converting this variable into digit will occur
NumberFormatException.
String s = "abc“ ;
P
int I = Integer.parseInt(s); // NumberFormatException
PP
4. If you are inserting any value in the wrong index, it would result
in ArrayIndexOutOfBoundsException as shown below:
P
• Classes for Exception Handling
EOFException
PP
FileNotFoundException
ArithmeticException
NumberFormatException
ArrayIndexOutOfBoundsException
NegativeArraySizeException
NoSuchMethodException
NoSuchFieldException
ClassNotFoundException etc.
Exception Handling
• Try Block
– It contains a block of statements that you want to monitor for
exception.
• Catch Block
– Immediately following the try block is a sequence of catch blocks.
– An argument is passed to each catch block to catch the exception
and handle it.
P
– Each catch block argument is type of exception.
• Finally Block
PP
– Contains a code that must be executed before a method returns.
– It must be executed either exception is generated or not.
• Throw Statement
– Manually throws an exception.
• Throws Clause
– To specify any exception that is thrown out of a method.
Syntax of Exception Handling
P
PP
Exception Handling
• If a problem occurs during execution of the try block, the JVM
immediately stops executing the try block and looks for a catch
block that can be process that type of exception. Any remaining
statements in the try block are not executed.
• The search beings at the first catch block. It the type of the
exception object matches the type of the catch block parameter,
those statements are executed. Otherwise, the remaining catch
P
clauses are examined in sequence for a type match.
PP
• When a catch block execution complete, control passes to the
statements in the finally block.
• Finally block must be execute either try block generate error or
not.
System.out.println("Before Division");
P
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
PP
System.out.println(i/j);
System.out.println("After Division");
}
catch(Exception e) {
System.out.println("main: " + e);
}
}
}
Example of Exception
public class Test {
public static void main(String args[]) {
try{
System.out.println("Before Division");
P
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
PP
System.out.println(i/j);
System.out.println("After Division");
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception"); }
}
}
Example of Exception
public class Test{
public static void main(String args[]) {
try {
int a = 50;
a = a / 0; // ArithmeticException
P
String s=null;
System.out.println( s.length() ); // NullPointerException
String str;
PP
str="Hello";
int i = Integer.parseInt(str); // NumberFormatException
int array1[];
array1=new int[5];
array1 [10]=50; // ArrayIndexOutOfBoundsException
}
Example of Exception
catch (ArithmeticException e) {
System.out.println("No. is Divide by Zero ");
}
catch (NullPointerException e) {
System.out.println("Null value in a variable");
}
P
catch (NumberFormatException e) {
System.out.println("Type coversion is illegal");
} PP
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out Of Bound Exception");
}
catch(Exception e) { // Other exceptions handling
System.out.println("Inbuilt exception is generated: " + e);
}
}
}
Catch block searches
• Exception handler begins at the first catch block
immediately following the try block in which the
exception occurred.
P
• The search continues until the type of the exception
PP
object matches the type of the catch block parameter.
• Syntax
P
catch (Exception Type param) {
….
…..
}
PP
throw param;
• Alternative Syntax
P
System.out.println("After a");
}
PP
catch(ArithmeticException e) {
System.out.println("main: " + e);
}
finally {
System.out.println("main: finally");
}
}
Exception Handling : Throw Statement
public static void a() {
try {
int i = 1;
int j = 0;
System.out.println("Before division");
System.out.println(i/j);
P
System.out.println("After division");
}
PP
catch(ArithmeticException e) {
System.out.println("d: " + e);
// search for the exception handler for object e in calling environment.
throw e;
}
finally {
System.out.println("a: finally");
} } }
Exception Handling: Throw Clause
E.g. Created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the Arithmetic
Exception otherwise print a message welcome to vote.
public class Test {
static void validate(int age){
P
if(age <18)
throw new ArithmeticException("not a valid age for voting ");
else
PP
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(19);
System.out.println("rest of the code...");
}}
Exception Handling: Throws Clause
• If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the method can
guard themselves against that exception. You can do this by including
a throws clause in the method’s declaration.
P
throw.
PP
• The java compiler checks each constructor and method to determine
the types of exceptions it can generate.
P
catch(ArithmeticException e) {
System.out.println(" Exception handler in Method a ::");
}
}
PP
public static void b() throws ArithmeticException {
c(); }
public static void c() throws ArithmeticException {
int no=10;
no=no/0; } }
Difference between throw and throws
P
PP
Streams
• The java.io package contains all the classes required for input and
output operations.
• Stream: an object that either delivers data to its destination (screen,
file, etc.) or that takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
• “Standard” I/O streams:
– System.in – defaults to the keyboard
– System.out – defaults to the monitor
P
– System.err – defaults to the monitor.
PP
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
P
int i=System.in.read(); //returns ASCII code of 1st character
System.out.println((char)i); //will print the character
PP
java.io Classes Hierarchy
The Streams can be divided into
Character Streams and
Byte Streams
Character Streams:
These streams are typically used to read and write text data.
P
Reader and Writer are classes for character streams in java.io.
PP
Reader that read characters & Writer that write characters.
Byte Streams:
These streams are typically used to read and write binary data
such as images and sounds.
InputStream that read bytes and
OutputStream that write bytes.
How to do I/O
import java.io.*;
P
• Open the stream
• Use the stream (read, write, or both)
PP
• Close the stream
FileWriter
• Java FileWriter class is used to write character-oriented
data to a file.
• Constructor
– FileWriter(String filepath)
– FileWriter(String filepath , boolean append)
– FileWriter(File fileobj)
P
• Methods
– It is used to write the string into FileWriter.
PP
void write ( String text)
– It is used to write some portion of string into FileWriter.
void write ( String s , int index, int size )
– It is used to write the char into FileWriter.
void write(char c)
– It is used to write char array into FileWriter.
void write(char[] c)
– void flush ( ) : It is used to flushes the data of FileWriter.
– void close ( ) : It is used to close the FileWriter.
FileReader
• Java FileReader class is used to read data from the file.
• Constructor
– FileReader(String filepath)
– FileReader(File fileobj)
P
• Reader Class Methods
PP
– It is used to return a character in ASCII form. It returns -1
at the end of file.
int read( )
P
fw.close();
int i;
PP
FileReader fr=new FileReader("D:\\testfile.txt");
P
PP
• Constructor
BufferedWriter Class
– BufferedWriter(Writer w) :Default bufsize is 8192 chars.
– BufferedWriter(Writer w , int bufsize)
• Methods
– void close() Closes the stream, flushing it first.
P
– void flush() Flushes the stream.
– void newLine() Writes a line separator.
PP
– void write(int c) Writes a single character.
• Methods
P
– int read() : Reads a single character.
PP
– String readLine() : Reads a line of text.
P
//FileWriter fw = new FileWriter(args[0]);
FileWriter fw = new FileWriter("D:\\a.txt");
PP
// Create a buffered writer
BufferedWriter bw = new BufferedWriter(fw,10);
// Write strings to the file
for(int i = 1; i <= 12; i++) {
bw.write("Line " + i + "\n"); }
// Close buffered writer
bw.close();
BufferedReader Class
// Create a file reader
//FileReader fr = new FileReader(args[0]);
FileReader fr = new FileReader("D:\\a.txt");
P
String s;
PP
// Read and display lines from file
P
String encoding)
• Method PP
– String getEncoding( )
• Returns the name of the character encoding .
• To read from a keyboard and convert into character
stream.
– InputStreamReader isr = new InputStreamReader (
System.in )
BufferedReader & BufferedWriter
import java.io.*; // Program - 1
class Test {
public static void main ( String args[] ) {
try {
//FileWriter fw = new FileWriter(args[0]);
P
//FileReader fr = new FileReader(args[0]);
FileWriter fw = new FileWriter("D:\\a.txt");
PP
FileReader fr = new FileReader("D:\\a.txt");
int i;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String sno, sname ; // store user input
String record = new String(); // store record data
BufferedReader & BufferedWriter
for ( i = 0 ; i < 2 ; i++) {
System.out.print("Enter the no::");
sno = br.readLine();
record = record.concat(sno);
P
PP
System.out.print("Enter the name::");
sname = br.readLine();
fw.write(record);
record = ""; }
BufferedReader & BufferedWriter
fw.close();
while ( ( i = fr.read() ) != -1 ) {
System.out.print( (char) i );
}
fr.close();
P
}
PP
catch(Exception e) {
System.out.println("e"+e);
}
}
}
Byte stream classes
P
PP
BufferedInputStream &
BufferedOutputStream
import java.io.*;
class Test {
public static void main(String args[]) {
try {
P
FileOutputStream fos = new FileOutputStream(args[0]);
//FileOutputStream fos = new FileOutputStream("D:\\a");
PP
BufferedOutputStream bos = new BufferedOutputStream(fos);
P
BufferedInputStream bis = new BufferedInputStream(fis);
// Read and display data
int i; PP
while((i = bis.read()) != -1) { System.out.println(i); }
// Close file input stream
bis.close();
}
catch(Exception e) {
System.out.println("Exception: " + e); } } }
Collections Framework
What is a Framework?
A framework is a set of classes and interfaces which provide a
ready-made architecture.
P
PP
•In Java, a separate framework named the “Collection
Framework” has been defined in JDK 1.2 which holds all the
collection classes and interface in it.
P
• Java ArrayList allows us to randomly access the list.
PP
• ArrayList can not be used for primitive types like int, char, etc. We will
need a wrapper class for such cases.
Collections Framework
// Java program to demonstrate the working of ArrayList in Java
import java.io.*; import java.util.*;
class Test {
public static void main(String[] args)
{ ArrayList<Integer> al = new ArrayList<Integer>();
P
// Printing elements
PP
System.out.println(al);
P
• The primary difference between a Vector and an ArrayList is that a
Vector is synchronized and an ArrayList is non-synchronized.
PP
• Synchronized means in a multithreading environment, it holds the
other threads in runnable or non-runnable state until current thread
releases the lock of the object.
Collections Framework
// Java program to demonstrate the working of Vector in Java
import java.io.*; import java.util.*;
class Test {
public static void main(String[] args)
{ Vector<Integer> v = new Vector<Integer>();
P
// Printing elements
PP
System.out.println(v);
P
PP
Introduction to the java.util package
• It Contains the collections framework, legacy collection classes, date
and time facilities, and miscellaneous utility classes ( a string
tokenizer, a random-number generator).
• Random class allows to generate random double , float, int , or long
numbers.
• Constructor
P
Random() :: It uses the current time as seed
Random( long seed )
• Instance Methods
nextInt()
PP
nextFloat()
nextLong()
nextDouble()
Introduction to the java.util package
import java.util.*;
class RandomInts
{
public static void main(String args[]) {
P
Random generator = new Random();
System.out.println(generator.nextInt());
PP
System.out.println(generator.nextFloat());
System.out.println(generator.nextDouble());
System.out.println(generator.nextLong());
P
concurrently and each part can handle a different task at the same
•
PP
time making optimal use of the available resources.
Multitasking is when multiple processes share common processing
resources such as a CPU.
• Multi-threading extends the idea of multitasking into applications
where you can subdivide specific operations within a single
application into individual threads.
• Each of the threads can run in parallel. The OS divides processing
time not only among different applications, but also among each
thread within an application.
Multithreading
• Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
• Each thread will have their own task and own path of execution in a
process.
• All threads of the same process share memory of that process, so
communication between the threads is fast.
P
• Multithreaded Applications
PP
• Text Editor : Microsoft Word allows the user to hit print, save, and
copy some portion, all at the same time. In this case three threads
are running: one in charge of printing, another saving, and a third
copying some portion.
• Web Browsers - A web browser can download any number of files
and web pages (multiple tabs) at the same time and still lets you
continue browsing. If a particular web page cannot be downloaded,
that is not going to stop the web browser from downloading other
web pages.
Multithreading
• Web Servers - A threaded web server handles each request with a
new thread. There is a thread pool and every time a new request
comes in, it is assigned to a thread from the thread pool.
• Computer Games - You have various objects like cars, humans, birds
P
which are implemented as separate threads. Also playing the
PP
background music at the same time as playing the game is an
example of multithreading.
Process & Thread
P
PP
Multithreading
• Process
– It is an instance of a program.
– It contains program code and its current activity.
• Thread
– A sequence of execution within a process.
P
– It is ‘lightweight’ process.
• Less time for Context switch.
PP
• Less space in memory and less resources.
– JVM manages threads and schedules them for
execution.
– A process having multiple threads that can share resources.
• Processes have their own memory space, threads share
memory
Multithreading
Thread class: It is in java.lang package
Constructors
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
P
Methods
public void start(): starts the execution of the thread.
PP
JVM calls the run() method on the thread.
P
public class ThreadDemo extends Thread {
public void run() {
PP
System.out.println("This code is running in a thread");
}
public static void main(String[] args) {
ThreadDemo thread = new ThreadDemo();
thread.start();
System.out.println("This code is outside of the thread");
}
}
Multithreading : Program 2
class ThreadX extends Thread {
public void run() {
try {
while(true) {
Thread.sleep(2000);
System.out.println("Hello");
P
}
}
PP
catch(InterruptedException ex) {
ex.printStackTrace(); } } }
class ThreadDemo1 {
public static void main(String args[]) {
ThreadX tx = new ThreadX();
tx.start();
} }
Multithreading : Program 3
[2] To implement the Runnable interface:
Running Threads:
If the class implements the Runnable interface, the thread can be
run by passing an instance of the class to a Thread object's
constructor and then calling the thread's start() method:
P
public class ThreadDemo implements Runnable {
public void run() {
}
PP
System.out.println("This code is running in a thread");
• When a class extends the Thread class, you cannot extend any
other class.
P
• Implementing the Runnable interface, it is possible to extend
PP
from another class as well
Networking
• TCP/IP sockets are used to implement reliable, bidirectional,
persistent, point-to-point, stream-based connections between
hosts on the Internet.
P
PP
• There are two kinds of TCP sockets in Java.
• One is for servers, and the other is for clients.
P
Creates a socket connecting the local host to the named
host and port
PP
• Socket(InetAddress ipAddress, int port)
Creates a socket using a preexisting InetAddress object
and a port
• InputStream getInputStream():
Returns the InputStream associated with the invoking socket.
P
• OutputStream getOutputStream():
PP
Returns the OutputStream associated with the invoking socket
P
try {
// Get port
PP
int port = Integer.parseInt(args[0]);
// Create server socket
ServerSocket ss = new ServerSocket(port);
// Create random number generator
Random random = new Random();
Networking :: ServerSocketDemo.java
// Create infinite loop
while(true) {
// Accept incoming requests
Socket s = ss.accept();
P
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
PP
dos.writeUTF("Random Number is: ");
dos.writeInt(random.nextInt());
// Close socket
s.close(); } }
catch(Exception e) {
System.out.println("Exception: " + e); } } }
Networking : SocketDemo.java
import java.io.*;
import java.net.*;
class SocketDemo {
public static void main(String args[]) {
try {
P
// Get server and port
String server = args[0];
PP
int port = Integer.parseInt(args[1]);
// Create socket
Socket s = new Socket(server, port);
// Close socket
P
s.close();
}
PP
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
Networking
• Store both the file ServerSocketDemo.java and
SocketDemo.java file in the same directory.
P
• To compile program type as below.
• > javac ServerSocketDemo.java
PP
• > javac SocketDemo.java
P
need a name and they can be implemented right in the body of
a method.
PP
Lambda expressions
Syntax
• The simplest lambda expression contains a single parameter
and an expression:
parameter -> expression
P
(parameter1, parameter2) -> expression
PP
• Expressions are limited. They have to immediately return a
value.
• Expressions can not contain variables, assignments or
statements such as if or for.
P
numbers.add(5); numbers.add(9);
numbers.add(8); numbers.add(1);
PP
System.out.println("Print Arraylist using for loop");
for(int i=0; i < numbers.size(); i++) {
System.out.println( numbers.get(i) );
}
System.out.println("Print Arraylist using Lambda
expression:");
numbers.forEach( (n) -> { System.out.println(n); } );
} }
Lambda expressions
interface Sayable{
public String say(String name);
}
public class Test {
public static void main(String[] args){
// Lambda expression with single parameter.
P
Sayable s1=(name)->{ return "Hello, "+name; };
System.out.println(s1.say("Shyam"));
PP
// You can omit function parentheses
Sayable s2= name ->{ return "Hi, "+name; };
System.out.println(s2.say("Kalpna"));
} }
lambda expressions : Multiple Parameters
interface Addable{
int add(int a,int b);
}
P
public static void main(String[] args) {
PP
// Multiple parameters in lambda expression
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
P
Arithop ad1=(a,b)->(a+b);
System.out.println(ad1.operation(10,20));
PP
// Multiple parameters with data type in lambda expression
Arithop ad2=(int a,int b)->(a-b);
System.out.println(ad2.operation(20,10));
P
read from the file and deserialized that is, the type information
and bytes that represent the object and its data can be used to
PP
recreate the object in memory.
P
• Similarly, the ObjectInputStream class contains the following
method for deserializing an object −
PP
public final Object readObject() throws IOException,
ClassNotFoundException
• Method retrieves the next Object out of the stream and
deserializes it.
• The return value is Object, so you will need to cast it to its
appropriate data type.
• E.g. Employee class, which implements the Serializable
interface −
Serialization
• For a class to be serialized successfully, two conditions must be met −
• The class must implement the java.io.Serializable interface.
• All of the fields in the class must be serializable. If a field is not
serializable, it must be marked transient.
• Example program instantiates an Employee object and serializes it to a
file.When the program is done executing, a file named employee.ser is
P
created. The we deserialize the employee.ser file in employee object and
display object data.
• The try/catch block tries to catch a ClassNotFoundException, which is
PP
declared by the readObject() method. For a JVM to be able to deserialize an
object, it must be able to find the bytecode for the class. If the JVM can't
find a class during the deserialization of an object, it throws a
ClassNotFoundException.
• Return value of readObject() is cast to an Employee reference.
• The value of the id field was 1001 when the object was serialized, but
because the field is transient, this value was not sent to the output stream.
The id field of the deserialized Employee object is 0.
Serialization
import java.io.*;
P
}
out.writeObject(e);
out.close();
P
fileOut.close();
catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
P
c.printStackTrace();
return;
} PP