KTU CST205 - M3
KTU CST205 - M3
KTU CST205 - M3
1
Syllabus
▪ Packages and Interfaces - Defining Package, CLASSPATH,
Access Protection, Importing Packages, Interfaces.
Exception Handling - Checked Exceptions, Unchecked
Exceptions, try Block and catch Clause, Multiple catch
Clauses, Nested try Statements, throw, throws and finally.
Input/Output - I/O Basics, Reading Console Input, Writing
Console Output, PrintWriter Class, Object Streams and
Serialization, Working with Files.
2
Packages
3
4
5
6
7
Predefined package
8
Creating Packages
▪ The general form of creating a package
is:
9
▪ To compile the java programs with
package use
▫ javac -d Destinationfolder
filename.java
10
▪ Package names and directory structure are
closely related.
▪ For example if a package name is
college.staff.cse
▫ Then there are three directories, college, staff
and cse such that cse is present in staff and
staff is present college.
11
▪ To use a class or a package from the
library, we need to use the import
keyword:
▪ Syntax
12
13
14
15
16
17
18
19
20
Interfaces
21
22
What is an interface in Java?
Interface looks like a class but it is not a class.
An interface can have methods and variables just
like the class but the methods declared in
interface are by default abstract
Also, the variables declared in an interface are
public, static & final by default.
23
What is the use of interface
in Java?
They are used for full abstraction
Since methods in interfaces do not have body, they
have to be implemented by the class before you can
access them
The class that implements interface must
implement all the methods of that interface.
Java programming language does not allow you to
extend more than one class, However you can
implement more than one interfaces in your class.
24
syntax
Interfaces are declared by specifying a keyword
“interface”. E.g.:
interface MyInterface{
/* All the methods are public abstract by
default as you see they have
no body */
public void method1();
public void method2();
25
}
26
27
28
29
30
31
Example
interface printable
public static void ma
{
in(String args[])
void print();
{
}
class A6 implements prin A6 obj = new A6();
table
obj.print();
{
}
public void print()
}
{
Output:Hello
System.out.println("Hell
32
o");
33
MODULE 3
1
Syllabus
▪ Packages and Interfaces - Defining Package, CLASSPATH,
Access Protection, Importing Packages, Interfaces.
Exception Handling - Checked Exceptions, Unchecked
Exceptions, try Block and catch Clause, Multiple catch
Clauses, Nested try Statements, throw, throws and finally.
Input/Output - I/O Basics, Reading Console Input, Writing
Console Output, PrintWriter Class, Object Streams and
Serialization, Working with Files.
2
I/O Basics
Let’s start with the first set of slides
3
Java I/O (Input and Output) is used to
process the input and produce the output.
Java uses the concept of a stream to make
I/O operation fast.
The java.io package contains all the
classes required for input and output
operations.
We can perform file handling in Java by
Java I/O API
4
Stream
5
A stream is a communication channel that a
program has with the outside world.
It is used to transfer data items in
succession.
An I/O Stream represents an input source or
an output destination.
A stream is a sequence of data.
In Java, a stream is composed of bytes.
It's called a stream because it is like a
stream of water that continues to flow.
6
Java Stream Classes
Based on the data they handle there are two
types of streams
Byte Streams
These handle data in bytes (8 bits)
Using these you can store characters,
videos, audios, images etc.
Character Streams
These handle data in 16 bit Unicode.
Using these you can read and write text
data only.
7
▪ In Java, 3 streams are created for us
automatically.
▪ All these streams are attached with the
console.
1. System.out : standard output
stream
2. System.in : standard input stream
3. System.err : standard error stream
8
▪ The code to print output and an error
message to the console.
▫ System.out.println("simple message");
▫ System.err.println("error message");
▪ The code to get input from console.
▫ int i=System.in.read(); //returns ASCII
code of 1st character
9
ByteStream
▪ This is used to process data byte by
byte (8 bits).
▪ The FileInputStream is used to read from
the source and FileOutputStream is used
to write to the destination.
▪ the FileInputStream and the
FileOutputStream are the most popular
ones.
10
▪ InputStream
▫ A program uses an input stream to read data
from a source.
▫ It may be a file, an array, peripheral
device or socket.
11
▪ InputStream class is an abstract class.
▫ It is the super class of all classes
representing an input stream of bytes.
12
InputStream - Methods
13
14
▪ Class DataInputStream extends FileInputStream and
implements the interface DataInput.
▪ Therefore, the DataInputStream class implements the
methods described in DataInput in addition to using the
methods of InputStream class.
▪ The DataInput interface contains the following methods
▫ readShort( )
▫ readInt( )
▫ readLong( )
▫ readFloat( )
▫ readUTF( )
▫ readDouble( )
▫ readLine( )
▫ readChar( )
▫ readBoolean( )
15
▪ OutputStream
▫ A program uses an output stream to write data
to a destination, one item at time
▫ It may be a file, an array, peripheral
device or socket
16
▪ OutputStream class is an abstract class.
▪ It is the superclass of all classes representing
an output stream of bytes.
▪ An output stream accepts output bytes and
sends them to some sink.
17
18
OutputStream - Methods
19
20
▪ The DataOutputStream implements the
interface DataOutput and therefore
implements the following methods contained in
Dataoutput interface.
▫ writeShort( )
▫ writeInt( )
▫ writeLong( )
▫ writeFloat( )
▫ writeUTF( )
▫ writeDouble( )
▫ writeBytes( )
▫ writeChar( )
▫ writeBoolean( )
21
STREAM CLASS DESCRIPTION
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
22
CharacterStream
▪ In Java, characters are stored using Unicode
conventions
▪ Character stream automatically allows us to
read/write data character by character
▪ FileReader and FileWriter are character
streams used to read from the source and
write to the destination respectively.
▪ the FileReader and the FileWriter are the
most popular ones
23
▪ Reader Classes
▷ Reader stream classes are used to read
characters from the files.
▷ It include a super class known as
Reader and a number of subclasses for
supporting various input-related
functions.
▷ The Reader class contains methods that
are is designed to handle characters.
24
25
▪ Methods of Reader class
Methods Description
int read() This method reads a characters from the input stream.
int read(char[] This method reads a chunk of characters from the input
ch) stream and store them in its char array, ch.
This method closes this output stream and also frees any
close()
system resources connected with it.
26
▷ Writer Classes
▷ the writer stream classes are designed
to perform all output operations on files.
▷ the writer stream are designed to write
character.
▷ The Writer class is an abstract class
which acts as a base class for all the
other writer stream classes.
▷ This base class provides support for all
output operations by defining methods
that are identical to those in
27 Outputstream class.
▪ Methods of Writer class
Methods Description
This method flushes the output steam by forcing out
abstract void flush()
buffered bytes to be written out.
This method writes a characters(contained in an int) to
void write(int c) the output stream.
This method closes this output stream and also free any
abstract void close()
resources connected with this output stream.
28
29
STREAM CLASS DESCRIPTION
PrintWriter This contains the most used print() and println() method
30
READING CONSOLE
INPUT
▪ In Java, there are three different ways for
reading input from the user in the command
line environment(console).
1. Using Buffered Reader Class
2. Using Console Class
3. Using Scanner class
32
Buffered Reader Class
▪ This is the Java classical method to take
input, Introduced in JDK1.0.
▪ This method is used by wrapping the
System.in (standard input stream) in an
InputStreamReader which is wrapped in a
BufferedReader, we can read input from
the user in the commandline.
33
Buffered Reader Class
▪ Advantage
▫ The input is buffered for efficient
reading
▪ Drawback
▫ The wrapping code is hard to
remember.
34
35
Console Class
▪ It has been becoming a preferred way for
reading user’s input from the command line.
▪ In addition, it can be used for reading
password-like input without echoing the
characters entered by the user
▪ The java.io.Console.format(String fmt,
Object... args) method writes a formatted
string to this console's output stream using
the specified format string arguments.
▫ Similar to printf in C
36
Console Class
▪ Advantages:
▫ Reading password without echoing the
entered characters.
▫ Reading methods are synchronized.
▫ Format string syntax can be used.
▪ Drawback:
▫ Does not work in non-interactive
environment (such as in an IDE).
37
38
WRITING CONSOLE OUTPUT
▪ Console output is most easily accomplished with print()
and println() methods.
▪ These methods are defined by the class PrintStream
which is the type of object referenced by System.in.
▪ Because the PrintStream is an output stream derived
from the OutputStream, it also implements the low-level
method write().
▪ Thus, write() can be used to write to the console.
▪ The simplest form of write() defined by the PrintStream is
shown below :
▫ void write(int byteval)
39
40
Scanner
Class
▪ most preferred method to take input.
▪ The Scanner class is used to get user
input
▪ it is found in the java.util package.
42
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
43
Method Description
44
Example
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
String name = myObj.nextLine();
int age = myObj.nextInt();
double salary = myObj.nextDouble();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
45
PrintWriter CLASS
▪ Java PrintWriter class is the implementation
of Writer class.
▪ It is used to print the formatted
representation of objects to the text-output
stream.
▪ Class declaration
▫ public class PrintWriter extends Writer
47
Method Description
PrintWriter append(CharSequence ch) It is used to append the specified character sequence to the
writer.
PrintWriter append(CharSequence ch, int start, int end) It is used to append a subsequence of specified character to
the writer.
boolean checkError() It is used to flushes the stream and check its error state.
PrintWriter format(String format, Object... args) It is used to write a formatted string to the writer using
specified arguments and format string.
48
49
Object Streams and
Serialization
50
▪ Java provides a mechanism, called object serialization where an
object can be represented as a sequence of bytes that includes the
object's data as well as information about the object's type and the
types of data stored in the object.
▪ Serialization in Java allows us to convert an Object to stream that we
can send over the network or save it as file or store in DB for later
usage
▪ Serialization in Java is a mechanism of writing the state of an
object into a byte-stream.
▪ Serialization is the process of converting an object into a stream of
bytes to store the object or transmit it to memory, a database, or a
file.
▪ After a serialized object has been written into a file, it can be read
from the file and deserialized that is, the type information and bytes
that represent the object and its data can be used to recreate the
object in memory.
51
▪ The serialization and deserialization process is platform-independent,
it means you can serialize an object on one platform and deserialize
it on a different platform
▪ The entire process is JVM independent,meaning an object can be
serialized on one platform and deserialized on an entirely different
platform.
▪ Classes ObjectInputStream and ObjectOutputStream are high-
level streams that contain the methods for serializing and
deserializing an object.
▪ For serializing the object, we call the writeObject() method of
ObjectOutputStream, and for deserialization we call the
readObject() method of ObjectInputStream class
▪ Its main purpose is to save the state of an object in order to be able
to recreate it when needed.
52
▪ We must have to implement the Serializable interface
for serializing the object.
▪ Advantages of Java Serialization
▫ It is mainly used to travel object's state on the
network (which is known as marshaling).
53
Object Stream class
▪ The above method serializes an Object and sends it to the
output stream. Similarly, the ObjectInputStream class
contains the following method for deserializing an object
▪ This 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
54
How it works?
Consider a class Employee
• The
ObjectOutputStream
class is used to serialize
an Object.
• SerializeDemo program
instantiates an Employee
object and serializes it to
a file.
• When the program is
done executing, a file
named employee.ser is
created.
• When serializing an
2
Files
3
▪ File handling is an important part of any
application.
▪ Data maintained in files is persistent
data because it exists beyond the
duration of program execution.
▪ Java has several methods for creating,
reading, updating, and deleting files.
▪ The File class from the java.io package,
allows us to work with files.
4
▪ The File class from the java.io package, allows
us to work with files.
▪ To use the File class, create an object of the
class, and specify the filename or directory
name
5
6
▪ Create a File
▫ To create a file in Java, you can use the
createNewFile() method.
▫ This method returns a boolean value: true if
the file was successfully created, and false if
the file already exists.
▫ the method is enclosed in a try...catch block.
▫ This is necessary because it throws an
IOException if an error occurs (if the file cannot
7
be created for some reason):
8
▪ Write To a File
▫ we use the FileWriter class together with its
write() method to write some text to the file we
created
▫ Note that when we are done writing to the file,
we should close it with the close() method
9
10
Read Files
11
Get File Information
12
Delete a File
• To delete a file in Java, use the delete() method:
13
Delete a Folder
14
Java FileInputStream
▪ The Java FileInputStream class, java.io.FileInputStream, makes it
possible to read the contents of a file as a stream of bytes.
▪ Java FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw
bytes) such as image data, audio, video etc.
▪ You can also read character-stream data. But, for reading
streams of characters, it is recommended to use
FileReader class.
▪ The Java FileInputStream class is a subclass of Java InputStream.
FileInputStream Constructors
▪ The FileInputStream class has different constructors you can
use to create a FileInputStream instance.
▪ Two commonly used constructors are
▫ FileInputStream(String filePath)
String path = "C:\\user\\data\\thefile.txt";
FileInputStream fileInputStream = new
FileInputStream(path);
Output:
success
Output:
success
▪ FileOutputStream(File file)
String path = "C:\\users\\jakobjenkov\\data\\
datafile.txt";
File file = new File(path);
FileOutputStream output = new
FileOutputStream(file);
Java FileOutputStream
constructors
▪ FileOutputStream(String name, boolean append)
OutputStream output = new
FileOutputStream("c:\\data\\output-
text.txt");
OutputStream output = new
FileOutputStream("c:\\data\\output-
text.txt", true); //append
OutputStream output = new
FileOutputStream("c:\\data\\output-
text.txt", false); //overwrite
FileOutputStream -
Important Methods:
Method Description
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 It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
void close() It is used to closes the file output stream.
Java FileReader
▪ The Java FileReader class, java.io.FileReader makes it
possible to read the contents of a file as a stream of
characters.
▪ It works much like the FileInputStream except the
FileInputStream reads bytes, whereas the FileReader
reads characters.
▪ The FileReader is intended to read text, in other words.
▪ One character may correspond to one or more bytes
depending on the character encoding scheme.
▪
Java FileReader
29
Java FileReader Example
Reader fileReader = new FileReader("c:\\data\\input-
text.txt");
int data = fileReader.read();
while(data != -1) {
//do something with data...
doSomethingWithData(data);
data = fileReader.read();
}
fileReader.close();
Constructors of FileReader
class
Constructor Description
It gets filename in string. It opens the given file in read
FileReader(String file) mode. If file doesn't exist, it throws
FileNotFoundException.
It gets filename in file instance. It opens the given file
FileReader(File file) in read mode. If file doesn't exist, it throws
FileNotFoundException.
Methods of FileReader class
Method Description
public int read() Reads a single character. Returns an int, which
represents the character read.
Public int read(char[] charArray) Used to read the specified characters into
an array
public int read(char [] charArray, int offset, int len) Reads characters into an array. Returns the number of
characters read.
public long skip(long n) skips the character.
n - It is the number of character to skip.
It returns the number of character which has been
skipped.
5
Common scenarios where exceptions
may occur
7
Common scenarios where exceptions
may occur
▪ Scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);
//NumberFormatException
8
Common scenarios where exceptions
may occur
▪ Scenario where ArrayIndexOutOfBoundsException
occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
9
Types of Java Exceptions
1
3
Error
▫ Error is irrecoverable
▫ e.g. OutOfMemoryError,
VirtualMachineError, AssertionError
etc.
1
4
Exception Handling
▪ Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException,RemoteException, etc
▪ The core advantage of exception handling is to maintain
the normal flow of the application
▪ An exception normally disrupts the normal flow of the
application that is why we use exception handling
▪ Exception handling ensures that the flow of the
program doesn’t break when an exception occurs
▪ Exception handling is one of the most important feature
of java programming that allows us to handle the runtime 1
errors caused by exceptions. 5
.
Exception Handling
▪ Let's take a scenario:
▫ Suppose there are 10
statements in your program
and there occurs an exception
at statement 5, the rest of the
code will not be executed i.e.
statement 6 to 10 will not be
executed.
▫ If we perform exception
handling, the rest of the
statement will be executed. 1
That is why we use exception 6
Java Exception Handling Keywords
1
7
try Block and catch
Clause
18
try…catch
try
{
//statements that may cause an
exception
}
catch (exception(type) e(object))
{
2
//error handling code 0
try …catch
2
1
22
23
Internal working of java try-catch
block
24
▪ The JVM firstly checks whether the exception is
handled or not.
▪ If exception is not handled, JVM provides a default
exception handler that performs the following tasks:
▫ Prints out exception description.
▫ Prints the stack trace (Hierarchy of methods where
the exception occurred).
▫ Causes the program to terminate.
▪ But if exception is handled by the application
programmer, normal flow of the application is
2
maintained i.e. rest of the code is executed. 5
Multiple catch
Clauses
26
Multiple catch Clauses
32
finally block
3
5
▪ Case 2 - Let's see the java finally example where
exception occurs and not handled.
3
6
▪ Case 3 - Let's see the java finally example where
exception occurs and handled
3
7
finally..
3
8
finally..
3
9
finally..
4
0
throw keyword
41
throw
▪ The Java throw keyword is used to explicitly throw an exception from
a method or any block of code.
▪ We can define our own set of conditions or rules and throw
an exception explicitly using throw keyword
▪ For example, we can throw ArithmeticException when we divide
number by 5, or any other numbers, what we need to do is just set
the condition and throw any exception using throw keyword.
▪ Throw keyword can also be used for throwing custom exceptions
▪ Syntax of throw keyword:
throw new exception-class("error message");
For example:
4
throw new ArithmeticException("dividing a number by 5 is not 2
allowed in this program");
43
Lets say we have a
requirement where we we
need to only register the
students when their age is
less than 12 and weight is
less than 40, if any of the
condition is not met then
the user should get an
ArithmeticException with
the warning message
“Student is not eligible for
registration”. We have
implemented the logic by
placing the code in the
method that checks student
eligibility if the entered
student age and weight
doesn’t met the criteria then
we throw the exception
using throw keyword.
4
4
throw..
▪ The flow of execution of the program stops immediately
after the throw statement is executed
▪ the nearest enclosing try block is checked to see if it has
a catch statement that matches the type of exception.
▪ If it finds a match, controlled is transferred to that
statement otherwise next enclosing try block is checked
and so on.
▪ If no matching catch is found then the default exception
handler will halt the program.
▪ instance must be of type Throwable or a subclass
of Throwable. 4
5
▪ For example Exception is a sub-class of Throwable
Output:
Caught inside
fun().
46
Caught in main.
throws keyword
47
throws
▪ The Java throws keyword is used to declare an
exception.
▪ throws is a keyword in Java which is used in the
signature of method to indicate that this method
might throw one of the listed type exceptions.
▪ The caller to these methods has to handle the
exception using a try-catch block.
▪ Exception Handling is mainly used to handle the
checked exceptions.
▪ 4
8
throws
▪ The throws does the same
thing that try-catch does but
there are some cases where
you would prefer throws over
try-catch.
▪ For example:
Lets say we have a
method myMethod() that has
statements that can throw
either ArithmeticException or But suppose you have several such methods
that can cause exceptions, in that case it
NullPointerException, in this would be tedious to write these try-catch for
case you can use try-catch each method. The code will become
as shown below: unnecessary long and will be less-readable.
. 4
9
throws
▪ One way to overcome this
problem is by using throws like
this:
▪ declare the exceptions in the
method signature using throws
and handle the exceptions where
you are calling this method by
using try-catch.
▪ Another advantage of using this
approach is that you will be
forced to handle the exception
when you call this method, all the
exceptions that are declared
using throws, must be handled
where you are calling this method
else you will get compilation error 5
0
throws..
▪ Syntax:
▫ type methodname(parameters) throws
exceptionlist
▫ exceptionlist is a comma separated list of
all the exceptions which a method might
throw.
5
1
52
53
54