Home
| | Sitemap
||Page number :22
A further study of java.io package
The “java.io” package contains classes that support java’s input & output system. The io package holds immense value as it contains several classes like “InputStreamReader” & “BufferedReader”. Thus the io package must be imported in each and every program for taking input from the console.
Once again have a look at an example that takes an input from its user.
import java.io.*; //importing all classes that are in the java.io package
class demoinp { public static void main(String args[]) throws IOException // "throws" keyword is used to // handle exception { String name; //An object of class String that takes a series of characters as an input int marks; // Variable that accepts the marks of user
InputStreamReader rd=new InputStreamReader(System.in); // Creating an object of the //class InputStreamReader
BufferedReader inp=new BufferedReader(rd); // Creating an object of the class // BufferedReader
System.out.println("Enter your Profile");
System.out.println("Enter your name"); // Message to the user name=inp.readLine(); // "name" getting the input
System.out.println("Enter your marks"); String v1=inp.readLine(); // Readline method used marks=Integer.parseInt(v1); // variable “mark” getting the input
if(marks>= 75 && marks<=100) System.out.println("Well Done!!!"); else if(marks>=50 && marks<75) System.out.println("Good,You can improve"); else if(marks>=0 && marks<50) System.out.println("You need to really work hard!!"); else System.out.println("Invalid Input"); } } Line 1: Importing the io package.
Line 11 & 13: We have created objects of two classes, InputStreamReader and BufferedReader. These classes help us to get an input as follows -
- InputStreamReader – Input Stream that translates bytes to characters
- BufferedReader ------BufferedReader wraps “System.in”, thus creating a character stream.
Line 19: Input is always received by the Java “Input Stream” in the form of a String (Strings are a series of characters & digits, e-g. “Hello”, “agh1”, “12”. The variable “name” gets the input with the help of the readLine() function.
Line 22 & 23: In the Line 22, we take the input in the form of String by the readLine() method. A variable “v1” gets the input. Then in the next line we have a statement that causes the variable “marks” to take the input as an Integer. A method Integer.parseInt(String name) accomplishes this task.
Remember:: There are two types of Streams in Java—
1. Byte Stream
2. Character Stream The byte stream is used for reading & writing binary data while the character Streams handle input & output of characters. Although at the basic level everything is in bytes.
page 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29