Nothing Special   »   [go: up one dir, main page]

Comprog - Java Chap 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

JAVA PROGRAMMING-CHAPTER 3

INPUT & OUTPUT STATEMENTS

Streams
JAVA programs perform input and output through streams. A
stream is either a source or destination for the data or
information. A stream in linked to a physical device by the JAVA
I/O stream. All streams in the same manner, even if the actual
physical devices to which they are linked differ. So the same I/O
classes and methods can be applied to perform I/O from any type
of device. Streams are the clean way to deal with input / output.
JAVA implements streams within class hierarchies defined in the
java.io package.

When you write data to a stream it is called Output Stream and


when you read data from a stream it will called Input Stream.

Two types of streams:


 Byte Streams
 Character Streams

Byte Streams
Byte streams provide easy way for handling input and output of
Bytes. These are used while reading and writing binary data. When
you write data to a stream as a series of bytes, it is written to the
stream exactly as it appears in memory. No transformation of data
takes place.

44
JAVA PROGRAMMING-CHAPTER 3

Byte streams are defined by using two class hierarchies. At the


top are two abstract classes: InputStream and OutputStream.
Each of these abstract classes has a number of concrete subclasses
that handle various different devices, such as disk, files, network
connections and even memory buffers.

The abstract classes InputStream and OutputStream define


several key methods that the other stream classes implement.
Two of the most important are read() and write(), which read and
write bytes of data. Both methods are declared as abstract inside
InputStream and OutputStream. They are overridden by derived
stream classes.

Character Streams
Character streams are used for storing and retrieving text from a
location or file by a JAVA program. All numeric data is converted
to textual from before being written to the stream. Reading
numeric data from the stream of characters involves much more
work than reading binary data.

Stream input and output methods generally permit very small


amount of data such as byte or char to be written and read in a
single operation. Sending data transfer like this would be
extremely inefficient, so stream is often equipped with a buffer,
which is called Buffered Stream.

Character streams are defined by using two class hierarchies. At


the top are two abstract classes: Reader and Writer. These
abstract classes handle Unicode character streams. JAVA has
several concrete subclasses of each of these.

45
JAVA PROGRAMMING-CHAPTER 3

The abstract classes Reader and Writer define several key


methods that the other stream classes implement. Two of the
most important are read() and write(), which read and write
characters of data. Both methods are declared as abstract inside
Reader and Writer. They are overridden by derived stream classes.

Buffered Streams
Buffered streams ensure that data transfer between memory and
external device are in large chunks to make this process efficient.
A buffer is simply a block of memory that is used to batch up a
data transfer. When you write to a buffered stream the data is
sent to buffer (not to external device). The amount of data in the
buffer is tracked automatically, and the data is sent to the device
when the buffer is full. You can do it manually by flushing the
buffer.

The Predefined Streams


All JAVA programs automatically import the java.lang package.
This package defines a class called System. It contains several
methods that can be used to obtain the current time and the
settings of various properties associated with the system. System
also contains three predefined stream variables; in, out and err.
These fields are declared as public and static within System. This
means that they can be used by any other part of the program
without reference to a specific System object.

System.out
Refers to the standard output stream. By default, this is the
console. System.in refers to the standard input, which is keyboard
by default. System.err refers to the standard error stream, which

46
JAVA PROGRAMMING-CHAPTER 3

is also console by default. However, these streams may be


redirected to any compatible I/O device.

System.in
An object of type InputStream; System.out and System.err are
objects of type PrintStream. These are byte streams, even though
they typically are used to read and write characters from and to
the console.

Reading Console Input


In JAVA 1.0, the only way to perform console input was to use a
byte stream, but the preferred method of reading console input
for JAVA 2 is to use a character oriented stream, which makes a
program easier to internationalize and maintain.

In JAVA, console input is accomplished by reading from System.in.


To obtain a character-based stream that is attached to the
console, you wrap System.in in a BufferedReader object, to create
a character stream. BufferedReader supports a buffered input
stream. Its most commonly used constructor is:
BufferedReader (Reader inputReader)
Here, input reader is the stream that is linked to the instance of
BufferedReader that is being created. Reader is an abstract class.
One of its concrete classes is InputStreamReader, which converts
bytes to characters. To obtain an InputStreamReader object that
is linked to System.in, use the following constructor:
BufferedReader (InputStream inputstream)

Because, System.in refers to an object of type InputStream, it can


be used for InputStream. Putting it all together, the following

47
JAVA PROGRAMMING-CHAPTER 3

lines of code create a BufferedReader that is connected to the


keyboard.

BufferedReader br = new BufferedReader (new


InputStreamReader(System.in);

After this statement executes, br is character-based stream that


is linked to the console through System.in.

Learning Exceptions

An exception is an unexpected or error condition. The programs


you write can generate many types of potential exceptions, such
as when you do the following:

 You issue a command to read a file from a disk, but the


files does not exist there.
 You attempt to write data to a disk, but the disks is full or
unformatted.
 Your program asks for user input, but the user enters
invalid data.
 The program attempts to divide a value by 0, access with
a subscript that is too large, or calculate a value that is
too large for the answer’s variable type.

These errors are called exceptions because, they are not usual
occurrences; they are “exceptional.” The object-oriented
techniques to manage such errors comprise the group of methods
known as exception handling.

48
JAVA PROGRAMMING-CHAPTER 3

Like all other classes in Java, exceptions are Objects. Java has
two basic classes of errors: Error and Exception. Both of these
classes descend from the Throwable class.

Error class represents more serious errors from which your


program usually cannot recover. Usually you do not use or
implement Error objects in your programs. A program cannot
recover from Error conditions on its own.
The Exception class comprises less serious errors that represent
unusual conditions that arise while a program is running and from
which the program can recover. Some examples of Exception class
errors include using an invalid array subscript or performing
certain illegal arithmetic operations.

Sample Program 3-1


Filename: ComputeAreaCircle.java

49
JAVA PROGRAMMING-CHAPTER 3

Sample Program 3-2


Filename: GetInfoTryCatch.java

import java.util.Scanner;
public class GetInfoTryCatch{
public static void main(String [] args){
int age;
String name, s_addr, gender;
try{
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your age: ");
age = inputDevice.nextInt();
inputDevice.nextLine();
System.out.print("Please enter your name: ");
name = inputDevice.nextLine();
System.out.print("Please enter your the address: ");
s_addr = inputDevice.nextLine();
System.out.print("Please enter gender: ");
gender = inputDevice.nextLine();
System.out.println();
System.out.println();
System.out.println(“Nice to meet you!” + name);
System.out.println(“You will turn “ + age+1 + ”next year”);
System.out.println(“May we visit you at “ + s_addr +”?”);
System.out.println(“Are you sure you are “ + gender + “?”);
}
catch(Exception e){
System.out.println("Error: " +e);
}
}
}

50
JAVA PROGRAMMING-CHAPTER 3

Sample Output Layout:

51
JAVA PROGRAMMING-CHAPTER 3

import java.io.*; you need the import java.io.*


to allow the user to use the java input and output
commands. The try and catch block is used for
catching and handling exception during execution
of the program. The use of try exception to handle
errors and other exceptional events and the catch
mechanism is used to detect and catch user input
errors.

 To input the value of the radius we need to create a


buffered class with an object as br1. This creates a
buffering character input stream that uses a default sized
input buffer.

 The InputStreamReader here works as a translator that


converts byte stream to character stream.

 Now use the parseInt() method of the Integer class in


order to convert from external numeric format to internal
format.

 Now create the Math class in which all the mathematical


functions are defined. This Math class can be imported
from the java.lang.* package.

Sample Program 3-3


Filename: GetUserInfoBR.java

52
JAVA PROGRAMMING-CHAPTER 3

Sample Program 3-4


Filename: Stud_Info.java

Throws IOException Java exception (exception


handling in Java). Exception, that means
exceptional errors, are used for handling errors
in programs that occurs during the program
execution. During the program execution if any error occurs
and you want to print your own message or system message
about the error then you write the part of the program which
generate the error in try {} block and catch the errors using
the catch {} block. Exception turns the direction of normal
flow of the program control and send to the related catch { }
block.

53
JAVA PROGRAMMING-CHAPTER 3

Sample Program 3-5


Filename: GetInfoThrowsIO.java

Math Class Methods in Java

Math class has different methods for finding power, absolute


value, min, max and rounding number etc.

Syntax:

Math.methods()
Here methods is replaced by different math class methods word

54
JAVA PROGRAMMING-CHAPTER 3

Syntax Function
Absolute Value. Here variable can be
double, float, int and long data type.
Math.abs(variable) abs method is used to find absolute
value of variable.
Math.abs(-2.3) = 2.3
Minimum Value. Here variable can be
double, float, int and long data type.
Math.min(variable1,v min method is used to find minimum
ariable2) value between variable1 and
variable2.
Math.min(2,8) = 2
Maximum Value. Here variable can be
double, float, int and long data type.
Math.max(variable1, max method is used to find maximum
variable2) value between variable1 and
variable2.
Math.max(2,8) = 8
Rounding Number. Here variable is
double data type. ceil method is used
Math.ceil(variable) round up the variable and floor method
is used round down the variable.
Math.floor(variable) Math.ceil(8.4) = 9
Math.floor(8.4) = 8
Power Of The Number. Here variable
is double data type. Variable1 is base
Math.pow(variable1, value and variable2 is power value.
variable2) Math.pow(2,3) = 8

55
JAVA PROGRAMMING-CHAPTER 3

Syntax Function

Square Root Of The Number. Here


variable is double data type. sqrt
method is used for finding square root
Math.sqrt(variable) of a number.
Math.sqrt(9) = 3
Cube Root Of The Number. Here
variable is double data type. cbrt
Math.cbrt(variable) method is used for finding cube root
of a number.
Math.cbrt(27) = 3
Copy Sign Of The Number. Here
variable is float and double data type.
copySign method is used to copy sign
Math.copySign(variab of variable2 and assign that sign to
le1, variable2) variable1.
Math.copySign(2,-8.3) = -2.0
Math.copySign(2,8.3) =
2.0
Math.exp(variable) Euler's Number e To Power Of A
Number. Here variable is double
data type. Euler's number e raised to
the power of a variable.
Math.exp(2) =
7.38905609893065

56
JAVA PROGRAMMING-CHAPTER 3

Syntax Function

Euler's Number e To Power Of A


Number Minus 1. Here variable is
Math.expm1(variable) double data type. Euler's number e
raised to the power of a variable
minus 1 is e^(variable)-1

Math.expm1(2)=6.3890560989306
5

Source: http://www.aboutcodes.com/2012/07/math-class-
methods-in-java-with-examples.html

57
JAVA PROGRAMMING-CHAPTER 3

Sample Program 3-6


Filename: JavaMathFunction
import java.util.Scanner;

public class JavaMathFunction{


public static void main(String angt[]){
Scanner data = new Scanner(System.in);
double num1,num2,num;
System.out.println("Enter a number"); num1=data.nextDouble();
System.out.println("Enter a number"); num2=data.nextDouble();

num=Math.abs(num1);
System.out.println("absolute:"+num);num=Math.min(num1,num2);
System.out.println("min:"+num);

num=Math.max(num1,num2);
System.out.println("max:"+num);num=Math.ceil(num2);
System.out.println("ceil:"+num);num=Math.floor(num1);
System.out.println("floor:"+num);num=Math.pow(num1, num2);
System.out.println("power:"+num);num=Math.sqrt(num1);
System.out.println("sqrt:"+num);num=Math.cbrt(num2);
System.out.println("cbrt:"+num);num=Math.copySign(num1,-8.2);
System.out.println("copysign:"+num);num=Math.exp(2);
System.out.println("exp:"+num);
num=Math.expm1(2);
System.out.println("expm1:"+num);
}
}

Sample output
layout:

58

You might also like