[Go to site: main page, start]

0% found this document useful (0 votes)
13 views7 pages

Java User Input Methods Explained

The document discusses various methods to take input in Java, focusing on the BufferedReader and Scanner classes. BufferedReader is efficient for reading character streams and requires exception handling, while Scanner is user-friendly and provides built-in methods for different data types. The document also highlights the differences between the two classes, noting that BufferedReader is faster and more flexible for larger inputs, whereas Scanner is easier to use for simple input tasks.

Uploaded by

meenasri025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Java User Input Methods Explained

The document discusses various methods to take input in Java, focusing on the BufferedReader and Scanner classes. BufferedReader is efficient for reading character streams and requires exception handling, while Scanner is user-friendly and provides built-in methods for different data types. The document also highlights the differences between the two classes, noting that BufferedReader is faster and more flexible for larger inputs, whereas Scanner is easier to use for simple input tasks.

Uploaded by

meenasri025
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Take Input from User in Java

There are various methods to get Input in Java.

Methods to Take Input in Java


There are two ways by which we can take Java input from the user or from a file
 BufferedReader Class
 Scanner Class
 Command Line Parameters

1). Using BufferedReader Class for String Input In Java


It is a simple class that is used to read a sequence of characters. It has a simple function read
that reads a character, another read which reads an array of characters, and a readLine()
function which reads a line.
InputStreamReader is a class that converts the input stream of bytes into a stream of
characters, allowing it to be read by BufferedReader, which expects a stream of characters.
Note: BufferedReader can throw checked exceptions.

Below is the implementation of the above approach:


// Java Program for taking user
// input using BufferedReader Class
import [Link].*;

class GFG
{
// Main Method
public static void main(String[] args) throws IOException
{
// Creating BufferedReader Object
// InputStreamReader converts bytes to
// stream of character
BufferedReader bfn = new BufferedReader(new InputStreamReader([Link]));

// String reading internally


String str = [Link]();
// Integer reading internally
int it = [Link]([Link]());

// Printing String
[Link]("Entered String : " + str);

// Printing Integer
[Link]("Entered Integer : " + it);
}
}
Output:
Mayank Solanki
888
Entered String : Mayank Solanki
Entered Integer : 888

Using Buffer Reader Class To Read the Input


Below is the implementation of the above approach:
import [Link].*;
import [Link];
import [Link];

class Easy
{
public static void main(String[] args)
{
// creating the instance of class BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
String name;
try
{
[Link]("Enter your name");
name = [Link](); // taking string input
[Link]("Name=" + name);
}
catch (Exception e)
{
}
}
}
Output:
Enter your name:
Geeks
Name=Geeks

2). Using Scanner Class for Taking Input in Java


It is an advanced version of BufferedReader which was added in later versions of Java. The
scanner can read formatted input. It has different functions for different types of data types.
 The scanner is much easier to read as we don’t have to write throws as there is no
exception thrown by it.
 It was added in later versions of Java
 It contains predefined functions to read an Integer, Character, and other data types as
well.

Syntax of Scanner class:


Scanner scn = new Scanner([Link]);

Importing Scanner Class:


‘To use the Scanner we need to import the Scanner class from the util package as
import [Link];

Inbuilt Scanner functions are as follows:


 Integer: nextInt()
 Float: nextFloat()
 String : next() and nextLine()

Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
It is used to scan the next token of the input into a boolean
boolean nextBoolean()
value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
BigDecimal It is used to scan the next token of the input as a
nextBigDecimal() BigDecimal.

Hence, in the case of Integer and String in Scanner, we don’t require parsing as we did require
in BufferedReader.
// Java Program to show how to take
// input from user using Scanner Class
import [Link].*;

class GFG
{
public static void main(String[] args)
{
// Scanner definition
Scanner scn = new Scanner([Link]);

// input is a string ( one word )


// read by next() function
String str1 = [Link]();

// print String
[Link]("Entered String str1 : " + str1);

// input is a String ( complete Sentence )


// read by nextLine()function
String str2 = [Link]();

// print string
[Link]("Entered String str2 : " + str2);

// input is an Integer
// read by nextInt() function
int x = [Link]();

// print integer
[Link]("Entered Integer : " + x);

// input is a floatingValue
// read by nextFloat() function
float f = [Link]();

// print floating value


[Link]("Entered FloatValue : " + f);
}
}
Output:
Entered String str1 : Geeks
Entered String str2 : Geeks For Geeks
Entered Integer : 123
Entered FloatValue : 123.090

Example-2:
// Java Program to implement
// Scanner Class to take input
import [Link].*;
import [Link];

// Driver Class
class Easy
{
// main function
public static void main(String[] args)
{
// creating the instance of class Scanner
Scanner obj = new Scanner([Link]);
String name;
int rollno;
float marks;

[Link]("Enter your name");

// taking string input


name = [Link]();
[Link]("Enter your rollno");

// taking integer input


rollno = [Link]();
[Link]("Enter your marks");

// taking float input


marks = [Link]();

// printing the output


[Link]("Name=" + name);
[Link]("Rollno=" + rollno);
[Link]("Marks=" + marks);
}
}
Output:
Enter your name
Geeks
Enter your rollno
5
Enter your marks
84.60
Name=Geeks
Rollno=5
Marks=84.60

Differences between BufferedReader and Scanner


 BufferedReader is a very basic way to read the input generally used to read the stream of
characters. It gives an edge over Scanner as it is faster than Scanner because Scanner
does lots of post-processing for parsing the input; as seen in nextInt(), nextFloat()
 BufferedReader is more flexible as we can specify the size of stream input to be read. (In
general, it is there that BufferedReader reads larger input than Scanner)
 These two factors come into play when we are reading larger input. In general, the
Scanner Class serves the input.
 BufferedReader is preferred as it is synchronized. While dealing with multiple threads it is
preferred.
 For decent input, and easy readability. The Scanner is preferred over BufferedReader.

Common questions

Powered by AI

Choosing between BufferedReader and Scanner involves a trade-off between ease of use and performance. Scanner provides ease of use with built-in methods for parsing different data types, reducing code complexity and eliminating the need for explicit parsing . However, BufferedReader offers better performance by not performing post-processing on data inputs, making it faster for large-scale data operations . Thus, BufferedReader is preferred for performance-critical applications, while Scanner is better for quicker development and applications where convenience matters more than speed .

BufferedReader requires explicit exception handling since it can throw IOException and also needs manual parsing of String inputs to other data types, increasing the chances of NumberFormatException . In contrast, the Scanner class does not throw checked exceptions for data conversion and has built-in methods for parsing different input types directly, simplifying error handling in applications . This difference makes Scanner a preferred option for developers looking to minimize exception handling complexity in their code.

BufferedReader and Scanner cannot be used interchangeably without altering program logic due to differences in functionality and parsing. BufferedReader reads input as simple character streams, requiring manual parsing and exception handling for data type conversions . In contrast, Scanner offers built-in type parsing which changes how input is read and handled . Thus, switching between them could necessitate changes to data processing and error handling logic in the program.

The choice affects both performance and ease of implementation. BufferedReader is beneficial in designs where performance with large datasets or stream processing is critical, as it offers faster processing due to its lack of parsing overhead . Conversely, Scanner simplifies implementation through its user-friendly, direct methods for data type conversion, which can streamline development and error handling . Thus, the application's requirements for performance, ease of use, and error handling complexity will guide this decision, potentially influencing both the code structure and runtime efficiency.

BufferedReader enhances flexibility by allowing specification of the size of the stream input to be read, making it faster for larger input as it reads larger input data in a single go compared to Scanner, which does a lot of post-processing for parsing . BufferedReader is preferred in scenarios dealing with large data input or when working with multiple threads, as it is synchronized .

Scanner provides built-in methods for reading and parsing various data types directly, such as nextInt(), nextFloat(), and nextLine(), eliminating the need for manual parsing or conversion. This contrasts with BufferedReader, which primarily reads strings, requiring additional steps to convert them to other data types and handling potential exceptions during parsing . As a result, Scanner offers greater convenience in scenarios requiring diverse data type inputs.

BufferedReader's synchronization ensures that input operations are thread-safe, making it a safer choice for multi-threaded applications. This synchronization, however, can introduce a performance overhead in single-threaded scenarios . In contrast, Scanner is not synchronized, making it possibly less safe in a multi-threaded context but potentially faster in single-threaded applications due to lack of synchronization overhead .

A developer might choose BufferedReader over Scanner for large files because BufferedReader reads character streams efficiently and can handle large input volumes without the overhead of parsing that Scanner performs. BufferedReader allows specifying the size of the input buffer, which can further enhance efficiency for large files . This makes it better suited for applications where large volumes of data need to be processed quickly and performance is crucial .

The Scanner class provides convenience over BufferedReader by offering predefined functions to directly read different data types such as int, float, double, and others without needing to parse the input manually, as required with BufferedReader . This eliminates the need for exception handling associated with parsing, making code simpler and more robust .

BufferedReader is considered faster than Scanner because it does not perform additional post-processing on the input data. Instead, it reads data directly as a stream of characters, which makes it efficient for handling large volumes of input data . This speed advantage makes BufferedReader suitable for programs where performance with large input is critical .

You might also like