Vous êtes sur la page 1sur 135

SESSION - 1

INPUT/OUTPUT/
INPUT DEVICE/OUTPUT
DEVICE
OBJECTIVES
Define input and
output
Define input device and output
device
Differentiate between input and input
device
Differentiate between output and
output device 1
INPUT & INPUT DEVICE
Input
any information needed by program to
complete execution
character input
mouse click
graphic input
audio input
file input, etc.

Input
computer peripherals used to accept input
device
keyboard
mouse
scanner
microphone
2
disks, etc.
OUTPUT & OUTPUT
DEVICE
Output
any information program conveys to user
display
printouts
engineering drawings
audio output
file output, etc.

Output
device
computer peripherals used to convey
output
monitor
printer
plotter
speaker
3
disks, etc.
INPUT/OUTPUT/
INPUT DEVICE/OUTPUT
DEVICE - Questions
1. Define input.
2. Define output.
3. What is input device.
4. What is output device.
5. Differentiate between -
a) Input and output
b) Input device and output
c) device
Input and input device
d) Output and output device
4
SESSION - 2
INPUT AND OUTPUT IN JAVA

OBJECTIVES

State how Java handles inputs and


outputs

Define Stream

State advantages of
Stream 5
JAVA PROGRAM
Java
mainly used for writing programs for the
Internet

Real-life applications of
Java
not text based console programs
graphically oriented
applets
rely upon Javas Abstract Window Toolkit -
(AWT)
for interaction with user
6
INPUT AND OUTPUT IN
JAVA
Regarded as stream of data

treated as sequence of data


flowing
source destination

c d
ab
d
a
b
c
a dc
b
Output stream
Input stream
7
ADVANTAGES OF STREAM
All streams behave in same
manner
even if linked physical devices
differ
Keyboard or mouse or scanner

Every part of a program


code
need not understand difference
between
keyboard network disk
can be connected to
various
data sources destinations
8
ADVANTAGES OF STREAM
(contd.)
Difference in codes for handling
different device
taken care of
not by programmer
by Application Programming Interfaces

Same I/O classes and methods can


be applied to any type of device
One program may have many
streams flowing in and many
9
INPUT AND OUTPUT IN JAVA -
Questions
1. Choose the correct
option -
a) Java language is usually used
for-
i. Application
programming
ii. System programming
iii.Internet programming
b) In Java inputs and outputs are usually -
i. Text oriented
ii. Graphic oriented
ii. Both
c) In Java inputs and outputs are regarded as -
i. Streams
ii. Characters
iii.Strings
10
2. Define Stream.
SESSION - 3
TYPES OF STREAM

OBJECTIVES

Name stream type

Differentiate between two stream types

State utility of each type


11
TYPES OF
Two STREAM
types

Byte stream Character stream

1 byte or 8 bits 2bytes or 16 bits

Before processing character stream is always


changed to byte stream.
12
DIFFERENCE BETWEEN BYTE
STREAM AND CHARACTER STREAM
Byte Character
stream
1 byte or 8 bits 2 bytes stream
or 16 bits
used for reading/writing used to read/write Unicode
binary data characters (From Java 1.1)
writes data directly input is written as character
e.g. 29813 stored as a e.g. 29813 is stored as 5
4-byte binary number different characters (array)
compact needs more space
converted to byte stream
offers direct access
for processing
efficient not as efficient
13
faster slower
TYPES OF STREAM -
Questions
1. Name different stream types.

2. How many bytes does each stream


occupy?

3. Write 3 differences between different


streams.

4. Which stream is used for processing?

5. How will the number 456 be stored in


each stream type? 14
SESSION - 4
System CLASS
OBJECTIVES

Defines package

Names the package which contains


System class

State the significance of System class


15
System CLASS
All Java programs automatically
import a package
A group of classes
java . lang

contains a class System

to handle input/output streams

provides static methods and


variables 16
System CLASS -
Questions
1. Define package.

2. Which package is automatically imported


in all Java programs?

3. Name a class defined in java.lang


package.

4. State the significance of System class.


17
SESSION - 5
STREAM VARIABLES OF
System CLASS
OBJECTIVES

Name stream variables

State utility of stream variables

18
STREAM VARIABLES OF System
CLASS
System class
contains three predefined stream variables
Store
input/outpu
t stream of
characters
in out err
automatically created
can be used
anywhere in the program ( public )

without reference to a specific object


19
( static )
STREAM VARIABLES OF
System CLASS - Questions

1. Name three stream variables of System


class which are automatically created.

2. What is the utility of the stream


variables?

3. Explain the implication of following terms


-
a) public

b) static 20
SESSION - 6
System . in

OBJECTIVES

State significance of
System . in

State default device

21
in
VARIABLE
Inputting data also called reading
data
managed by stream variable -
in
refers to standard input stream

by default stores data coming from


keyboard

in
variable

data

INPUT DEVICE 22
PROCESSOR
System .
in
System . in
used to create object of InputStream classes or
Scanner class
created to copy data from System . in

can be accepted by using methods like -


read( ), readLine ( ) next( ),nextLine( )

Of BufferedReader class Of Scanner


in
classObject of
variable InputStream
class

data
INPUT DEVICE 23
PROCESSOR
System . in - Questions
1. What is the utility of stream variable in?

2. By default data from which device is


stored in stream variable in?

3. Which class object is created using


System . in?
4. What is the advantage of creating
System.in object?

5. What is meant by reading of data?


24
SESSION - 7
System . out

OBJECTIVES

State significance of System .


out

State default device

25
out
VARIABLE
Outputting data writing/printing data

managed by stream variable -


out
refers to standard output stream

by default sends data to console or


monitor

out
variable

data 26
PROCESSOR OUTPUT DEVICE
System .
out
System .
out
can be used with methods like -

print( ), println
()

to display data

out
variable

27
PROCESSOR OUTPUT DEVICE
System . out - Questions
1. What is the utility of stream variable out?

2. By default which device is data sent to


from out stream variable?

3. Which class object is created using


System . out?
4. What is the advantage of creating
System.out object?

5. What do you mean by reading/printing of


data? 28
SESSION - 8
System . err
OBJECTIVES

State significance of
System . err

State default device

29
err
VARIABLE
Run-time errors are sent to output
devices
managed by stream variable -
err
refers to standard output stream for error
messages
by default sends data to console or
monitor

err
variable

data 30
PROCESSOR OUTPUT DEVICE
System .
err
System .
err
can be used -

for handling exceptions

run-time errors

err
variable

31
PROCESSOR OUTPUT DEVICE
System . err - Questions
1. What is the utility of stream variable err?

2. By default which device is data sent to


from stream variable err?

3. Which class object is created using


System . err?
4. What is the advantage of creating
System.err object?

5. What are exceptions?


32
STREAM VARIABLES
All three streams can be redirected to any
compatible I/O device

A program may have several input


streams and several output streams

Java programs read and write one


character at a time from and to the
streams
Streams can be managed easily using
methods in java.io or java.util packages
33
OBJECTS OF System
CLASS - Questions

1. Can the in, out and err objects be


redirected to any other device than the
default device?

2. How many streams can be handled in a


program?

3. How is a stream of data written into input


stream or the output stream?
34
SESSION - 9
INPUT IN JAVA
OBJECTIVES

Explains problem of handling inputs

States reason of problems in handling


inputs
35
INPUT IN
JAVA
Java inputs
getting from user is more
complicated
than displaying output

are more error prone


than its output

If wrong, may crash down causing exception


run time error
are accepted as string
values
Java does not have any generalised
36
input method.
INPUT IN JAVA -
Questions
1. Why Java do not have any generalised
input method?

2. State the problems faced during


accepting inputs from the keyboard in a
Java program.

3. Why handling of input is tougher than


handling output in Java?

4. What is the data type of the accepted


37
SESSION - 10
TYPES OF INPUT IN JAVA
OBJECTIVES

State types of input

Differentiate between types of


input
38
TYPES OF INPUT IN JAVA
Two types

Command Run
line time
Given while calling main Given while the
method program is executed

cannot be used to display can be used to display a


a menu before accepting menu before accepting
any input any39input
DIFFERENCE BETWEEN
COMMAND LINE INPUT & RUN
TIME INPUT
COMMAND LINE RUN TIME
Given while calling main Given while the program
method is executed
Stored in array defined Can be stored in arrays,
with main method variables, instance
variables
Cannot be used for menu Can be used for menu
selection selection

Each value should be Numeric values need not


enclosed in a pair of double be enclosed in double
quotes quotes
40
Prompt cannot be used Prompt should be used
TYPES OF INPUT IN JAVA -
Questions

1. Name different types of input in Java.

2. What are the differences between


different types of input of Java?

3. Why prompt cannot be used with


command line inputs? 41
SESSION - 11
COMMAND LINE INPUT
OBJECTIVES
Define

Explain significance of different


commands
State how and when to type inputs

Use in programs 42
COMMAND LINE INPUT
Information passed into a method
during method call.
Arguments directly follow the
method name on the command line
method call
line
Multiple arguments can be passed
to a method.
With comma in between
arguments
Argument
s Should be included within double

quotes
Stored as string values in a String43
COMMAND LINE INPUT -
STATEMENTS
A String array should be declared
in main method declaration
as
line
e.g.- public static void main ( String args [] )
parameter
String inputs can be directly
assigned to variables
e.g.- String name = args [ 0 ] ;
Numeric inputs can be converted to
numbers from string
using methods of corresponding wrapper
class
contains methods to handle primitive data
e.g.- int roll = Integer . parseInt ( args [ 1 ] ) ;
type
float salary = Float . parseFloat 44( args [ 2 ] ) ;
long empno = Long . parseLong ( args [ 3 ] ) ;
COMMAND LINE INPUT
VALUES
Should
be
typed when method is called
enclosed in double quotes
Multiple inputs can be
typed
should be separated by a
comma
Inputs typed are
serially stored in array defined as parameter
Care should be taken
values typed in command line should match
arguments used in
45
numbe type order
COMMAND LINE INPUT
e.g.
Accept name and rate of a chocolate
and number of packets bought.
Calculate the amount to be paid.
Display all the details.
Class CommandLineInput
{ public static void main ( String args [ ] )
{ String name = args [ 0 ] ;
float rate = Float . parseFloat ( args [ 1 ] ) ;
int packets = Integer . parseInt ( args [ 2 ] ;
float amount = rate * packets ;
System . out . println
(Name\t\tRate\t\tQuantity\t\tAmount ) ;
System . out . println ( name + \t\t
46 + rate +
\t\t + packets + \t\t + amount ) ; } }
COMMAND LINE INPUT
VALUES
While calling the main method the
values should be typed as-
(assuming-
chocolate name Cadburys Fruit and
Nuts, rate Rs. 25,
no. of packets bought 5 )
main() { Cadburys Fruit and Nut , 25 , 5 }
If the above sequence is changed to -
1. main() { 25 , Cadburys Fruit and Nut , 5 }
Program will give run time error as name cannot be stored in
variable float rate.

2. main() { Cadburys Fruit and Nut , 5 , 25 }


Program will store 5 in rate variable and 25 in packets
47 variable.
COMMAND LINE INPUT
Questions
1. What are command line inputs?
2. When and how are the input values
typed?
3. Which separator is used between the
values?
4. Where are the accepted values stored?
5. What is a wrapper class?
6. How are the numeric values converted
from String type to corresponding number
type?
7. In what respects should the variables
48
and
values match?
SESSION - 12
RUN-TIME INPUT

OBJECTIVES

Define

State and explain different types

49
RUN TIME INPUT
Inputs
typed
during program execution
on the output screen
one at a time
preceded by a prompt

Use -
a java package to use library classes
to handle inputs
object of Scanner/BufferedReader class
50
CLASSES HANDLING
RUN-TIME INPUT
Two types
Byte stream Character stream

handled by handled by

Subclasses of BufferedReader class


InputStream and and Scanner class
OutputStream, e.g.
-DataInputStream class
Scanner class is stored in java.util package
Other three classes stored in java.io
51 package
RUN-TIME INPUT
Questions
1. Define run-time input.

2. How many types of run-time input are


there?
3. Name the class that is used for byte
stream inputs.

4. Name the classes that are used for


character stream inputs.

5. Which package store the classes used for


run-time inputs?

6. What are the three elements used


52
in a
program to handle run-time inputs?
POINTS TO NOTE

Most of the functionality


available for byte streams is
also provided for character
streams. The methods for
character streams generally
accept parameters of data type
char, while byte streams work
with byte data types. 53
POINTS TO NOTE
Unless working with binary data, such as
image and sound files, readers and writers
(character streams) classes should be used
to read and write information for the following
reasons:
can handle any character in the Unicode
character set (while the byte streams are
limited to ISO-Latin-1 8-bit bytes).
easier to internationalize because they are
not dependent upon a specific character
encoding.
use buffering techniques internally and are
therefore potentially much more efficient
54
than
byte streams.
SESSION - 13
SCANNER CLASS
OBJECTIVES

State use

Explain significance of different


commands used

Accept inputs using different


commands
Use in programs 55
SCANNER CLASS
Scanner class in
Java
introduced in

version 1.5.0
as a teaching tool for beginners
to take keyboard input
without having to deal with handling
checked exceptions
some exceptions handled by
class
without programmers intervention
56
SCANNER CLASS
Utilise java . util package in the
program
using import statement
before class declaration

e.g.- import java . util . Scanner ;


class ScannerClassInput { .}
OR import java .
util . * ;
class ScannerClassInput { .}
with first form of import statement
Only the Scanner class of java . util package can
be used
with second form of import statement
57
all classes of java . util package can be
SCANNER CLASS
Create an object of Scanner class -
to accept inputs
having System.in object as constructor
parameter
method ~ puts initial values in object variables
values/variables passed to other methods
e.g.- import java . util . * ; class
ScannerClassInput { public static void
main ()
{ Scanner scan = new Scanner ( System . in ) ;
. } } 58
INPUTS USING SCANNER
CLASS
Use next () method to read one
word
using Scanner class object name

e.g.- import java . util . * ; class


ScannerClassInput { public static void
main ()
{ Scanner scan = new Scanner ( System . in );
System . out . print ( First name : ) ;
String name = scan . next () ; }
}

*NOTE** - If multiple words are typed as input -


only the first word is stored in the variable - 59
name
INPUTS USING SCANNER
CLASS
Use nextLine() method to accept
multiple words
using Scanner class object

e.g.- import java . util . * ; class


ScannerClassInput { public static void
main ()
{ Scanner scan = new Scanner ( System . in );
System . out . print ( First name : ) ;
String name = scan . next () ;
System . out . print ( Address : ) ;
String address = scan . nextLine () ;
} }
60
INPUTS USING SCANNER
CLASS
Use the following methods to
accept primitive data types
nextByte ( ), nextShort ( ), nextInt ( ) ,
nextLong ( ), nextFloat ( ) , nextDouble ( ),
nextBoolean ( )
e.g.- import java . util . * ; class
ScannerClassInput { public static void
main ()
{ Scanner scan = new Scanner ( System . in );
System . out . print ( First name : ) ;
String name = scan . next () ;
System . out . print ( Address : ) ;
String address = scan . nextLine () ;
System . out . print ( Basic salary : ) ; 61
float basic = scan . nextFloat() ; } }
INPUTS USING SCANNER
CLASS
Use stored inputs for
processing
e.g.- import java . util . * ; class
ScannerClassInput { public static void
main ()
{ Scanner scan = new Scanner ( System . in );
System . out . print ( First name : ) ;
String name = scan . next () ;
System . out . print ( Address : ) ;
String address = scan . nextLine () ;
System . out . print ( Basic salary : ) ;
float basic = scan . nextFloat() ;
float da = basic * 80 / 100 ;
float gross = basic + da;
System.out.println(Name : +name+
\Address : +address+\nBasic : 62
+basic+\nGross : + gross ) ;} }
hasNextXxx ( ) METHOD OF SCANNER
CLASS
Most files contain a great deal of
data
programs process this data using loop
writing one record at a time in an String
object
hasNextxxx method is used as a test expression
before copying data in the next field in a
variable
to avoid exception

These methods
returntrue fals
e
if data type of next if data type of next token
token in scanner's in scanner's input does
input matches not match

does not advance past any input


hasNextXxx ( ) METHOD OF SCANNER
CLASS
Methods available of this format
are -
hasNextByte ( hasNextFloat ( )
)
hasnextShort ( ) hasNextDouble ( )

hasNextInt ( ) hasNextBoolean ( )

accepts true or false


hasNextLong ( )
PROGRAM USING
hasNextxxx ( )
import java . util . * ;
public class ScannerClassMethods
{ public static void main ( )
{ String inp = "1234 Surabhi 25906 30000 25.4 10.5" ; //One record
Scanner scan = new Scanner ( inp ) ; //For picking values from record
int sal [ ] = new int [ 3 ] , i = 0 , j = 0 ;
String name = "" , line = "-----------------------------------" ;
double rates [ ] = new double [ 2 ] ;
while ( scan . hasNext( ) )
{if ( scan . hasNextInt ( ) ) { sal [ i ] =scan.nextInt();i ++; }
else if(scan.hasNextDouble()){rates[j]=scan.nextFloat() ;j++;}
else name = scan . next ( ) ; }
double cca = sal [ 1 ] * rates [ 0 ] / 100 ;
double gross = sal [ 1 ] + sal [ 2 ] + cca ;
double pf = rates [ 1 ] * sal [ 1 ] / 100 ;
double net = gross - pf ;
System.out.println("Employee No.: "+sal[0]+"\nName : "+
name);
System.out.println("\nBasic : " + sal [ 1 ] +65"\nCCA : " +
cca ) ;
OUTPUT OF
PROGRAM USING hasNextxxx (
)
Employee No.: 1234
Name : Surabhi

Basic : 25906
CCA : 6580.123901176453

HRA : 30000
--------------------------------------------
Gross : 62486.123901176456

PF : 2720.13
--------------------------------------------
Net : 59765.99390117646
--------------------------------------------
66
SESSION - 14
BufferedReader CLASS
OBJECTIVES

Define

Explain significance of different


commands used

Accept inputs of different data


types
Use in programs 67
BufferedReader CLASS
Include java . io package in the
program
using import statement
before class declaration

e.g.- import java . io . * ;


class CharacterStreamInput
{ .}

It is better to import all classes of java . io package as


character input stream uses two classes-
InputStreamReader class of java . io package
BufferedReader class of java . io package
68
BufferedReader CLASS
Handle run time errors (exceptions)
during input handling

using throws IOException keyword

with method declaration

e.g.- import java . io . * ; class


CharacterStreamInput {
public static void main () throws IOException
{ .. } }
69
InputStreamReader CLASS

Console input stored in


System . in
passed to object of subclass of
InputStream
InputStreamReader

bridge between byte stream and character


stream
reads stream of bytes
decodes them into characters
70
BufferedReader CLASS
Statements
Create an object of
InputStreamReader class
to work with character stream
having System.in object as constructor
parameter
e.g.- import java . io . * ; class
CharacterStreamInput {
public static void main () throws IOException
{
InputStreamReader isr = new
InputStreamReader ( System . in ) ;
.. } } 71
BufferedReader CLASS

BufferedReader class -
buffers (stores) input send by user
improve efficiency
inputs can be send continuously
internal processing using each data goes on side by side

reduces waiting time of CPU


when it has to interact with a device

as devices are slower than computers processor

has many convenient methods to72 read


BufferedReader CLASS
Statements (contd.)
Create a BufferedReader
object
to utilise methods of BufferedReader
using InputStreamReader object as constructor
parameter
e.g.- import java . io . * ; class
CharacterStreamInput { public static void
main () throws IOException { InputStreamReader
isr = new InputStreamReader ( System .
in ) ; BufferedReader input =
new BufferedReader ( isr ); .. } }

Creation of both objects can be done


as -BufferedReader input = new BufferedReader
e.g.- 73
( new InputStreamReader(System . in) );
BufferedReader CLASS
Prompt the user information to be
typed
using System . out . print
statement
Use read () method to read one
character
returns -1 at end of stream, else returns as integer 0
to 65535
using BufferedReader object
e.g.- import java . io . * ; class
CharacterStreamInput { public static void
main () throws IOException { BufferedReader input
= new BufferedReader ( new
InputStreamReader(System . in) );
System.out.print( Debit card or Credit card
(Type D or C)? );
74
char card = (char) input . read () ; . } }
INPUTS OF BufferedReader
CLASS
Use readLine() method to read string
values
reads a line or string of data terminated
by enter
using BufferedReader object
e.g.- import java . io . * ;
class CharacterStreamInput
{ public static void main () throws IOException
{ BufferedReader input = new BufferedReader
( new InputStreamReader(System .
in) );
System.out.print( Debit card or Credit card
(Type D or C)? );
char card = (char) input . read
75 () ;
System . out . print(Card holder name : );
INPUTS OF BufferedReader
CLASS
All inputs stored as strings in
System .string
Convert in values to
numbers
using methods of corresponding wrapper
e.g.-
class
import java . io . * ; class
CharacterStreamInput
{ public static void main () throws IOException
{ BufferedReader input = new BufferedReader
( new InputStreamReader(System . in) );
System.out.print(Debit card or Credit card (D / C)?);
char card = (char) input . read () ;
System . out . print(Card holder name : );
String name = input . readLine () ;
System . out . print ( Card number : ) ; long
cardno = Long.parseLong (input.readLine () ) ;
System . out . print ( Amount due : ) ; float
amount =Float.parseFloat ( (input.readLine()) ; 76 .. } }
INPUTS OF BufferedReader
CLASS
Use stored inputs for
processing
e.g.- import java . io . * ; class
CharacterStreamInput { public static void
main () throws IOException { BufferedReader
input = new BufferedReader ( new
InputStreamReader(System . in) );
System.out.print(Debit card or Credit card (D / C)?);
char card = (char) input . read () ;
System . out . print(Card holder name : );
String name = input . readLine () ;
System . out . print ( Card number : ) ; long
cardno = Long.parseLong (input.readLine () ) ; System .
out . print ( Amount due : ) ; float amount
=Float.parseFloat ( (input.readLine()) ;
float minamt = amount * 5 / 100 ;
System . out . print ( Minimum amount to be paid : +
77
minamt ) ; .. } }
BufferedReader CLASS
INPUT
import java . io e.g.
.*;
public class CharacterStreamInput
{ public static void main () throws IOException
{ BufferedReader input = new
BufferedReader (new
InputStreamReader (System . in ) ); System . out .
print (Enter your name : ) ; String name =
input . readLine();
System.out.print(Enter purchase amount : ) ;
float amt = Float.parseFloat(input.readLine() ) ;
System . out . print (Are you a member ) ;
char ans = (char) input . read () ;
String extra = input . readLine () ; if
( amt >= 1000 && ans == Y || ans == y )
System.out.println(name+! You get a watch free);
else 78
System.out.println(name+! You get a chocolate
BufferedReader CLASS
INPUT Questions
1. What is prompt?
2. Which object reads input from console?
3. What is the function of
4. InputStreamReader
What is the utility ofclass?
BufferedReader
5. class?
Write syntax of creating objects of
InputStreamReader and BufferedReader
classes -
a) separately
b) .together
.
6. What does readLine() method
do? does read() method
7. What
return - a
a) on reading
79
b) character?
at the end of
SESSION - 15
EXCEPTION HANDLING
OBJECTIVES

Define

Explain significance of different


commands used

Accept inputs using different


commands
Use in programs 80
ERRORS IN JAVA
A program may give errors at various
stages

during
compilation

at run time

in the output as erroneous results


81
ERRORS IN JAVA
ERRORS

Compile-time error Run-time error Logical error

Errors detected by Errors trapped in Errors cannot be detected


compiler run time either by compiler or by
interpreter
Stops compilation Stops program Does not stop
execution compilation or program
execution

Should be corrected Should be corrected Should be corrected and


and then recompiled and then program then program should be
should be compiled compiled and run
and run

Usually syntax error Also called Exceptions Usually


82 error in
sequence of statements
ERRORS IN JAVA
e.g. of compile-time error-
int res = a(b/c);
** Gives error as there is no operator between a and (

e.g. of run-time error-


int roll = Integer . parseInt ( args [ 0 ] ) ;
** if the value is typed as Dhoni the program will Give
NumberFormatException error as a string value cannot be stored in a
variable of int type

e.g. of logical error-


int no1 , no2 , sum=no1+no2; no1 =
Integer . parseInt (args[0]) ; no2 = Integer .
parseInt (args[1]) ; ..
83
** Gives wrong result as sum added before accepting the inputs
EXCEPTIONS IN JAVA
A program that accepts run-time
inputs -
should be safeguarded against exceptions

run time errors

this restriction ensures

entered data

is valid

does not corrupt existing


database 84
EXCEPTION HANDLING
Internally exception is handled as
object
When an exception occurs
program control passes to either
default handler generated by interpreter
displays name of relevant exception class
displays at which point exception occurred
terminates program
exception handler code written by
programmer
code written by programmer to take care of run time
errors is called Exception Handling 85
EXCEPTION HANDLING
All exception types are handled by
code in pre-written class Throwable
has two main
subclasses
Error
Exceptio
When an
n exception
occurs
JVM stores error in object of Exception class
can be utilised by programmer
to -
display a relevant error message
86 86
continue with next part of program
KEYWORDS HANDLING
EXCEPTION
5 keywords used by programmers to
handle exceptions
try

catch

throw

throws

finally 87
KEYWORDS try AND catch
try and catch statements work as a
group
try
statements to be monitored for
exceptions
written within try block
exception occurring involving code in try
block
trapped and thrown by interpreter
remaining statements in try block
bypassed
catch
exception thrown by interpreter
caught using catch blocks
handled by the programmer in rational
manner 88
one catch block written for each exception type
KEYWORD finally
Keyword
finally
used to include code
that absolutely must be executed
before program execution
stops
passes to next part of
program
usually statements to close all open files
written in this block

written after all catch blocks


After executing finally block
89
execution continues with next part of
try, catch AND finally
Note :
The try block cannot be present without either catch
clause or finally clause.

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses whenever a


try/catch block is present.

No code should be written in between the try, catch,


finally blocks.

Unlike other Exception handling keywords-

try, catch, finally


prevent the program from automatically
PROGRAM USING try, catch,
finally
import java . io . * ;
class ExceptionHandling
{ public static void main ()
{ BufferedReader input = new BufferedReader ( new InputStreamReader ( System . in ) ) ;
int numb1 = 0 , numb2 = 0 , quo ;
try { System . out . print ( "Enter a number : " ) ;
numb1 = Integer . parseInt ( input . readLine () ) ;
System . out . print ( "Enter another number : " ) ;
numb2 = Integer . parseInt ( input . readLine () ) ;
quo = numb1 / numb2 ;
System . out . println ( "Quotient -> " + quo ) ; } //try
catch (ArithmeticException e)
{ System.out.println("Sorry! No. 2 should not be zero.");}
catch (NumberFormatException e)
{System.out.println("Sorry! You need to type a no.");}
catch ( IOException e ) {System . out . println
( "Sorry! There is an error in input." ) ;}
finally { System . out . println ( "This is to try out finally block. \nNumbers
are :" + numb1 + " and " + numb2 ) ;} //finally
int sum = numb1 + numb2 ; System . out . println ( "Sum is
: " + sum ) ; } }

91
OUTPUT OF PROGRAM USING
try, catch, finally
1. Enter a number : 200
Enter another number : 10
Quotient -> 20
This is to try out finally block.
Numbers are :200 and 10
Sum is : 210

2. Enter a number : 25
Enter another number : 0
Sorry! No. 2 should not be zero.
This is to try out finally block.
Numbers are :25 and 0
Sum is : 25

3. Enter a number : m
Sorry! You need to type a no.
This is to try out finally block.
Numbers are :0 and 0
Sum is : 0 92
KEYWORDS throw AND
throws
throw -
used to throw errors explicitly

from catch block

flow of execution stops immediately after


throw

throws -
throws error out of the method

exception carried to the calling


method 93
used in method
/** Accept name of the user and change it to initials and last name. */
import java . io . * ; import java . util . * ;
public class ChangeNameToInitial
{ public static void main () throws IOException
{ BufferedReader input = new BufferedReader
( new InputStreamReader ( System . in ) ) ;
String name , initial = " " , longest = "" ;
int len , i , j , len1 , worlen = 0 ;
System . out . print ( "Enter your name : " ) ;
name = input . readLine ( ) ;
String words [ ] = name . split ( ) ; len = words . length ;
for ( i = 0 ; i < len; i ++ )
{ len1 = words [ i ] . length ( ) ;
if ( worlen < len1 ) { worlen = len1 ; longest = words [ i ] ;} }
for ( j = 0 ; j < i - 1 ; j ++ )
initial = initial + Character . toUpperCase
( words [ j ] . charAt ( 0 ) )+ "." ;
initial = initial + words [ i ] ; 94
PROGRAM USING throw
import java . io . * ;
class ThrowIOException
{ public static void main ()
{ BufferedReader input = new BufferedReader ( new InputStreamReader
( System . in ) ) ;
int numb = 0 ; float squareRoot = 0 ;
try { System . out . print ( "Enter a number : " ) ;
numb = Integer . parseInt ( input . readLine () ) ;
if ( numb > 0 ) squareRoot = (float) ( Math .sqrt ( numb ) ) ;
System . out . println ( "Square Root -> " + squareRoot ) ; }
catch ( IOException e ) {System . out . println ( "Sorry! There is an error in
input." ) ;}
catch (NumberFormatException e){System.out.println("Sorry! You need to
type a no.");
throw e ;}
int square = numb * numb ;
System . out . println ( "Square is : " + square ) ; } }
OUTPUT
Enter a number : m
Sorry! You need to type a no. 95
** After this control comes to edit window with the error
DIFFERENCE BETWEEN
throw AND throws
throw throws

Used in method body Used with method


declaration

Used to enforce Cannot enforce


user-defined exceptions user-defined exceptions

Can be used to pass a Cannot be used to pass


custom error message custom error messages

One keyword handles One keyword may handle


one exception multiple exceptions 96
EXCEPTION HANDLING
Questions
1. Differentiate between different types of
error. Give an example of each.
2. What is Exception Handling?
3. Which keywords are used to handle
exceptions?
4. What is the utility of try and catch
keywords?
5. Which class handles all the errors? Name
two subclasses of that class.
6. What is the utility of keyword finally?
7. Differentiate between keyword throw and
keyword throws.
97
8. Define exception.
SESSION - 16
OUTPUT IN JAVA
OBJECTIVES

Define

Explain significance of different


commands used

Accept inputs of different data


types
Use in programs 98
OUTPUT IN
JAVA
System class declares out object of
PrintStream class
handles standard output stream
defines two methods for easy handling of
console display
print( println(
) successive next successive
next ) output takes
output takes place at next line a newline
place at same character (\n) gets added end
line of the text being displayed.

Both methods used with System.out


variable
e.g.- System . out . print ( Hello! ) ;
System . out . println ( How are you? 99) ;
ESCAPE SEQUENCE
CHARACTERS
print() and println() methods use
escape sequence characters
formatting
non graphicalof display
characters
characters cannot be entered directly
preceded by \
enclosed within a pair of (double quotes)
or (single quotes)
\ Display single quotes
\ Display double quotes
\\ Display back slash
\n New line or line feed
\t Tab of 8 characters
\b Backspace
100
OUTPUT IN JAVA e.g.
Program
import
- java . io . * ;
public class CharacterStreamInput
{ public static void main ()
{ System . out . println (\t\t* ) ;
System . out . print(\t*\t* ) ;
System . out . print (\t*\n) ;
System . out . print ( *\t*\t* ) ;
System . out . println ( \t*\t* ) ;
System . out .
println(\t*\t*\t*\n\t\t*); } }
Output -
*
* * *
* * * * *
* * * 101
*
SESSION - 17
PRINTING IN JAVA
OBJECTIVES

Define

Name the classes and interfaces

Explain the utility 102


PRINTING IN JAVA
Classes for printing on printer
java . awt
stored in- . print package
Printing involves-
deciding what to print
make appropriate printer ready for job
a print job created for every document
printed
Print job-
a unit of work to be run on a printer
consisting of one or more files

A unique job number assigned to


103
each print job received by printer
PRINTING IN JAVA
While printing
a given page
sent to printer at given time

pages
may be rendered multiple
times
out of sequence

Advantages
Optimises usage of printer memory
by printing only a part at a time
Pages may also be printed in reverse
104 order
PAGE RENDERING MODEL
Two models of rendering pages to
a print job-

Printables

Pageables

105
PRINTABLES
Printables
simpler of the two printing
models
uses one PagePainter for entire document
pages rendered in sequence
starting at page
zero
if a few pages rendered (say 5 through 7)
print subsystem asks for all pages up to last
page (here upto seventh page)
prints only pages five, six and seven
total pages to be printed not displayed
Implemented through Printables106
PAGEABLES
Pageables
offer flexibility
each page can feature a different layout
mostly used with Books class
handles a collection of pages having
different formats
characteristics
each page can have its own painter or
a painter for cover page, another painter for table of
format
contents, third for entire document
mix of portrait and landscape pages can be
used
print pages out of sequence, pages may
be skipped
does not need to know no. of pages
107 in
Implemented
document through Pageables
PRINTER CLASS
Java also has a library class named
Printer
represents an IBM AS/400 printer

an instance of this class used to manipulate


an individual AS/400 printer.

subclass of
java . lang . Object 108
OUTPUT IN JAVA
Questions
1. Which object handles standard output
stream?
2. Which class declares methods to display
on screen?
3. What are the two methods used for
display?
4. Write the difference between two display
methods.
5. What are escape sequence
characters?
6. Name two of the most frequently used
escape sequence characters. How are
7. they
Writedenoted?
a statement to display -
109
The commentator shouted, G O A L
ASSIGNMENT
1. A courier company delivers parcels at the
following rate
Within the city
Upto 5 gms. Rs. 25/=
Above 5 gms. - Rs. 40/= for every
10 gms.
Outside the city
The rates are double
Write a program in Java to accept from
the user whether the destination address
is within city or not and also the weight
of the parcel in gms. Calculate110the
ASSIGNMENT
2. A company has employees who are divided into
four grades as follows:
Grade Basic DA HRA (Rs.
per month) (% of Basic) (% of Basic)
1 10,000 or more 40
30 2 5,000 - < 10,000 40
25
3 < 5,000 but > 2,000 30
20
4 2,000 or less 30 15

If Net salary (Basic+DA+HRA) is above Rs.50,000


per month then Income Tax at the rate of 30% of
the annual salary exceeding 50,000 is deducted
on monthly basis at source. Taking name of the
employees and the Basic (monthly) pay as
inputs, a pay slip, which contains Name,
111 Grade,
Basic monthly pay, DA, HRA, Monthly Income Tax
ASSIGNMENT
3. A cloth showroom has announced the
following festival discounts on the
purchase of items, based on the total
cost of the items purchased
Total cost Discount (in %)
Less than 2000 5%
Rs. 2001 - Rs. 5000 25%
Rs. 5001 - Rs. 10000 35%
Above Rs. 10000 50%
Write a program to input the total cost
and to compute and display the amount
to be paid by the customer after
112 availing
ASSIGNMENT
4. Accept two numbers. Without using the
modulus operator display whether the
lower number is a factor of the higher
number.
5. Write a Java class Times to accept time
taken to finish two assignments by
storing hours, minutes and seconds in
different variables for both the works.
Find the total time taken to finish the
assignments. The output should be
displayed as follows:
Assignment I - tot hours: tot minutes:
113
tot seconds
import java.io.*; public class
InsufficientFundsException extends
Exception { private double amount;
public
InsufficientFundsException(double
amount) { this.amount = amount; }
public double getAmount() { return import java.io.*; public class
amount; } } CheckingAccount { private double
balance; private int number; public
public class BankDemo { public static void CheckingAccount(int number)
main(String [] args) { CheckingAccount c = { this.number = number; } public void
new CheckingAccount(101); deposit(double amount) { balance +=
System.out.println("Depositing $500..."); amount; } public void withdraw(double
c.deposit(500.00); try amount) throws
{ System.out.println("\nWithdrawing InsufficientFundsException { if(amount
$100..."); c.withdraw(100.00); <= balance) { balance -= amount; } else
System.out.println("\nWithdrawing $600..."); { double needs = amount - balance;
c.withdraw(600.00); } throw new
catch(InsufficientFundsException e) InsufficientFundsException(needs); } }
{ System.out.println("Sorry, but you are short public double getBalance() { return
$" + e.getAmount()); e.printStackTrace(); } } } balance; } public int getNumber()
{ return number; } }
SESSION - 5
BYTE STREAM AND
CHARACTER STREAM
OBJECTIVES

Name classes in each stream

Describe some features of the classes

116
BYTE STREAM
Byte stream
Has two main
classes
InputStream OutputStream
Takes byte oriented input stream Creates byte oriented output
stream

Both are abstract classes

object cannot be created but other classes can inherit from


it

117
CHARACTER
STREAM
Character stream
Has two main
classes

Reader Writer
Takes character oriented input Takes byte oriented input
stream stream
Changes to byte oriented Changes to character oriented
output stream output stream

For processing data is changed into byte stream


Character stream is used as it is easier for man
machine interaction 118
BYTESTREAM & CHARACTER
STREAM
Byte stream and character stream
classes
InputStream, OutputStream, Reader,
Writer
have many subclasses

handle different

devices

memory buffers

119
STREAMS OF JAVA -
Questions
1. What are the two types of streams?

2. Write three differences between two


types of stream.

3. How will the number 35 be stored in


different stream types?

4. Name two main classes of each stream


type.
5. At lower level how is a character stream
handled?
6. What is the advantage of character stream
data over the other type? 120
SESSION - 15
BYTE STREAM INPUT
OBJECTIVES

Define

Explain significance different


commands used
Accept inputs of different data
types
Use in programs 121
BYTE STREAM INPUT -
STATEMENTS
Utilise java . io package in the
program
using import statement
before class declaration

e.g.- import java . io . DataInputStream ;


class ByteStreamInput { .}
OR import java . io .
*;
class ByteStreamInput { .}
with first form of import statement
DataInputStream class of java . io package can be
used
with second form of import statement
122
all classes of java . io package can be
STATEMENTS OF
BYTE STREAM INPUT
Handle run time errors (exceptions)
during input handling
using throws IOException
keyword identifier

with method declaration

e.g.- import java . io . * ; class


ByteStreamInput {
public static void main () throws IOException
{ } }
123
BYTE STREAM INPUT -
STATEMENTS
Create an object of DataInputStream
type
to accept inputs
having System.in object as constructor
parameter
method ~ puts initial values in object variables
variables receiving values from other methods
e.g.- import java . io . * ; class
ByteStreamInput { public static void
main () throws IOException { DataInputStream
input = new DataInputStream
( System . in ) ; . } } 124
INPUTS OF BYTE STREAM
Use read () method to read one
character
using DataInputStream object
name
e.g.- import java . io . * ; class
ByteStreamInput { public static void
main () throws IOException { DataInputStream
input = new DataInputStream ( System
. in ) ; char grade = (char) input . read () ;
} }

**NOTE** - type casting of input to (char) is must to pick up


one character at a time, as System . in
is
buffered
store multiple characters 125
input not passed to program until ENTER key
INPUTS OF BYTE STREAM
Use readLine() method to accept
multiple characters
using DataInputStream object

Accepting String values -

e.g.- import java . io . * ; class


ByteStreamInput { public static void
main () throws IOException { DataInputStream
input = new DataInputStream
( System . in ) ; char grade = (char) input . read
() ; String name = input . readLine () ;
.. } }
126
INPUTS OF BYTE STREAM
All inputs stored as strings
Convert String to numeric
values
using one of the methods of corresponding
wrapper class
e.g.- import java . io . * ; class
ByteStreamInput { public static void
main () throws IOException { DataInputStream
input = new DataInputStream
( System . in ) ; char grade = (char) input . read
() ; String name = input . readLine () ;
int eno = Integer.parseInt (input.readLine());
float basic = Float . parseFloat
((input.readLine()); . } } 127
USING INPUTS OF BYTE
STREAM
Use stored inputs for
e.g.- import java . io . * ; class
processing
ByteStreamInput { public static void
main () throws IOException { DataInputStream
input = new DataInputStream
( System . in ) ; char grade = (char) input . read
() ; String name = input . readLine () ;
int eno = Integer.parseInt (input.readLine());
float basic = Float . parseFloat
((input.readLine()); float da = basic *
80 / 100 ; float gross = basic + da , tax = 0
, net ; if (grade==A) tax = .3*(basic-500000);
net = gross tax ;
System.out.println(Name : +name+ \nEmp. no. :
+eno+\nBasic : +basic } }
128
FLOW OF INPUT IN BYTE
STREAM
import java . io . * ;
Lets compiler use prewritten Makes all the classes of java . io
classes in a package package available

DataInputStream input ; // method declatration

Class name, object type Object name

input = new DataInputStream (System . in ) ;


Operator creates variables of object Creates link DataInputStream object and System. in variable
reserves space initialise instance/object variables

String name = input . readLine();


Variab
Method allows user to type input to le1
System,in to DataInputStream object MEMORY UNIT
to variable
Variab
le2
System.in DataInputStream
variable Variab
object
le3

Variab
129 le4
BYTE STREAM INPUT e.g.
import java . io . * ;
public class ByteStreamInput
{ public static void main () throws IOException
{ DataInputStream input = new
DataInputStream (System . in ) ;
System . out . print (Enter your
name : ) ; String name = input . readLine();
System . out . print (Enter your age :
); int age =
Integer.parseInt(input.readLine() ) ; System . out .
print (Are you Indian (Y/N) ) ; char ans = (char)
input . read () ; if ( age >= 18 &&
ans == Y || ans == y )
System.out.println(name+! You can vote.); else

System.out.println(Sorry + name+! 130


You
BYTE STREAM INPUT
Questions
1. Which class handles the byte input
2. streams?
In which package are the I/O classes
3. stored?
Which statement is used to include a
package in a program?
4. Write the syntax of including -
a) all the classes of a package in a
b) program.
a particular class of a package in a program.
5. What are the run time errors called?
6. Which keyword is used to handle run time
errors? Which statement is it used with?
Give an
7. Name example.
the method used to read -
a) Input
a) stream
One character from Input 131

stream
POINTS TO NOTE
Prior to JDK 1.1, the input and output
classes (mostly found in the java.io
package) only supported 8-bit byte streams.
The concept of 16-bit Unicode character
streams was introduced in JDK 1.1. While
byte streams were supported via the
java.io.InputStream and
java.io.OutputStream classes and their
subclasses, character streams are
implemented by the java.io.Reader and
java.io.Writer classes and their subclasses.
132
hasNextInt()
Most files contain a great deal of data. Practical programs must process this
data using a loop of some sort. Here is a program that reads a text file that
contains many integers and writes the square of each one. The loop reads
integers from the file one by one until the end of file is reached or non-
integer input is encountered.
import java.util.Scanner; import java.io.*; class ManySquares { public static
void main (String[] args) throws IOException { File file = new
File("myData.txt"); // create a File object Scanner scan = new Scanner( file );
// connect a Scanner to the file int num, square; while( scan.hasNextInt() ) //
is there more data to process? { num = scan.nextInt(); square = num * num ;
System.out.println("The square of " + num + " is " + square); } } } The
hasNextInt() method returns true if the next set of characters in the input
stream can be read in as an int. If they can't be read as an int, or if the end
of the file has been reached, then it returns false.

133
java . awt . print PACKAGE
java . awt . print package has -
three interfaces
Printable
Pageable
PrinterGraphic
s
four classes
PageFormat
PrinterJob
Paper
Book 134
EXCEPTION HANDLING
All exception types are handled by
code in pre-written class Throwable
has two main
subclasses
Error
Exceptio
When an
n exception
occurs
JVM stores error in object of Exception class
can be utilised by programmer
to -
display a relevant error message
135
continue with next part of program

Vous aimerez peut-être aussi