Input in Java With
Input in Java With
InputStreamReader + BufferedReader.
Main Method Declaration public static void main(String args[]) throws IOException
Keywords Explanation
public: Accessible from anywhere
Here, public is the keyword used to specify that the function has no restriction on being used
anywhere throughout the system.
int n;
System.out.println("Enter a number:");
n = Integer.parseInt(in.readLine());
Accepting Float and Double Values
float f; double d;
System.out.println("Enter a real number:"); System.out.println("Enter a real number:");
f = Float.parseFloat(in.readLine()); d = Double.parseDouble(in.readLine());
Accepting a Character
Characters are read using read() method.
Needs to be explicitly cast to char type.
char ch;
System.out.println("Enter a character:");
ch = (char) in.read();
Accepting a String
Strings are directly accepted using readLine().
String str;
System.out.println("Enter a string:");
str = in.readLine();
Prog. 1 In a class of 'n' number of students, the number of girls is 'm'. Write a
program to input the values of n and m. Find and display the percentage of
boys and girls in the class.
// To find and display the area and perimeter by using Input Stream
import java.io.*;
public class Square
{
public static void main(String args[]) throws IOException a = d/Math.sqrt(2)
{ ar=a*a;
InputStreamReader read=new InputStreamReader(System.in); p=4*a;
BufferedReader in=new BufferedReader(read); System.out.println("The area = "+ar);
double a,d,p,ar;
System.out.println("The perimeter = "+p);
System.out.println("Enter the diagonal of a square");
}
d=Double.parseDouble(in.readLine());
}
Summary and Key Takeaways
• InputStreamReader converts byte stream to character stream.
• BufferedReader allows fast, buffered reading of text.
• Both classes work together to enable efficient and flexible input handling.
• Suitable for handling various data types from the console.
• More reliable than Scanner in certain complex I/O operations.