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

Emo 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
13 views10 pages

Emo 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses
Tutorials
Java
Practice
Contests

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
How to Take Input From User in Java?
Scanner Class in Java
Java.io.BufferedReader Class in Java
Difference Between Scanner and BufferedReader Class in Java
Ways to read input from console in Java
System.out.println in Java
Difference between print() and println() in Java
Formatted Output in Java using printf()
Fast I/O in Java in Competitive Programming
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
How to Take Input From User in Java?
Last Updated : 23 Jul, 2024
Java brings various Streams with its I/O package that helps the user perform all
the Java input-output operations. These streams support all types of objects, data
types, characters, files, etc. to fully execute the I/O operations. Input in Java
can be with certain methods mentioned below in the article.

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
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 java.io.*;

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(System.in));

// String reading internally


String str = bfn.readLine();

// Integer reading internally


int it = Integer.parseInt(bfn.readLine());
// Printing String
System.out.println("Entered String : " + str);

// Printing Integer
System.out.println("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 java.io.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Easy {
public static void main(String[] args)
{
// creating the instance of class BufferedReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String name;
try {
System.out.println("Enter your name");
name = reader.readLine(); // taking string input
System.out.println("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(System.in);
Importing Scanner Class:
‘To use the Scanner we need to import the Scanner class from the util package as

import java.util.Scanner;
Inbuilt Scanner functions are as follows:
Integer: nextInt()
Float: nextFloat()
String : next() and nextLine()
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 java.util.*;

class GFG {

public static void main(String[] args)


{
// Scanner definition
Scanner scn = new Scanner(System.in);

// input is a string ( one word )


// read by next() function
String str1 = scn.next();

// print String
System.out.println("Entered String str1 : " + str1);

// input is a String ( complete Sentence )


// read by nextLine()function
String str2 = scn.nextLine();

// print string
System.out.println("Entered String str2 : " + str2);

// input is an Integer
// read by nextInt() function
int x = scn.nextInt();

// print integer
System.out.println("Entered Integer : " + x);

// input is a floatingValue
// read by nextFloat() function
float f = scn.nextFloat();

// print floating value


System.out.println("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 java.io.*;
import java.util.Scanner;

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

System.out.println("Enter your name");

// taking string input


name = obj.nextLine();
System.out.println("Enter your rollno");

// taking integer input


rollno = obj.nextInt();
System.out.println("Enter your marks");

// taking float input


marks = obj.nextFloat();

// printing the output


System.out.println("Name=" + name);
System.out.println("Rollno=" + rollno);
System.out.println("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.
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

rexsunar37010

Previous Article
Wrapper Classes in Java
Next Article
Scanner Class in Java
Read More
Down Arrow
Similar Reads
How to Take Array Input From User in Java
There is no direct method to take array input in Java from the user. In this
article, we will discuss two methods to take array input in Java. But first, let's
briefly discuss arrays in Java and how they differ from other programming
languages. Array in Java is a group of like-typed variables referred to by a common
name. Arrays in Java work differ
6 min read
ArrayBlockingQueue take() method in Java
ArrayBlockingQueue is bounded, blocking queue that stores the elements internally
backed by an array. ArrayBlockingQueue class is a member of the Java Collections
Framework.Bounded means it will have a fixed size, you can not store number the
elements more than the capacity of the queue.The queue also follows FIFO (first-in-
first-out) rule for stor
3 min read
LinkedBlockingQueue take() Method in Java with Examples
The take() method of LinkedBlockingQueue is used to retrieve and remove the head of
this queue. If the queue is empty then it will wait until an element becomes
available. This method is more efficient if working on threads and using
LinkedBlockingQueue in that process. So the thread that initially calls take() goes
to sleep if there is no element
4 min read
PriorityBlockingQueue take() method in Java
The take() method of PriorityBlockingQueue returns head of the queue after removing
it. If queue is empty, then this method will wait until an element becomes
available. Syntax: public E take() throws InterruptedException Returns: This method
returns value at the head of this PriorityBlockingQueue. Exception: This method
throws InterruptedException
2 min read
LinkedTransferQueue take() method in Java
The java.util.concurrent.LinkedTransferQueue.take() method is an in-built function
in Java which retrieves and remove the first element of the queue. This method also
waits (if necessary) until an element becomes available. Syntax:
LinkedTransferQueue.take() Parameters: The function does not accept any parameter.
Return Value: The function returns
2 min read
LinkedBlockingDeque take() method in Java
The take() method of LinkedBlockingDeque returns and removes the head of the Deque
container from it. The method throws an InterruptedException if it is interrupted
while waiting. Syntax: public E take() Returns: This method returns the head of the
Deque container. Exception: The function throws a InterruptedException if it is
interrupted while wai
2 min read
DelayQueue take() method in Java with Examples
The take() method of DelayQueue is used to retrieve head of the DelayQueue and also
removes it. Thus, the size of the DelayQueue is reduced. This function waits if an
element with expired delay is available on this queue. Syntax: public E take ()
Parameters: This method accepts no parameters.Return Value: The function returns
the head of the DelayQ
2 min read
BlockingDeque take() method in Java with Examples
The take() method of BlockingDeque returns and removes the head of the Deque
container from it. The method throws an InterruptedException if it is interrupted
while waiting. Syntax: public E take() Returns: This method returns the head of the
Deque container. Exception: The function throws a InterruptedException if it is
interrupted while waiting.
2 min read
BlockingQueue take() method in Java with examples
The take() method of BlockingQueue interface is used to retrieve and remove the
head of this queue. If the queue is empty then it will wait until an element
becomes available. This method is more efficient if working on threads and using
BlockingQueue in that process. So the thread that initially calls take() goes to
sleep if there is no element av
4 min read
How to Take a Screenshot in Selenium WebDriver Using Java?
Selenium WebDriver is a collection of open-source APIs used to automate a web
application's testing. To capture a screenshot in Selenium, one must utilize the
Takes Screenshot method. This notifies WebDriver that it should take a screenshot
in Selenium and store it. Selenium WebDriver tool is used to automate web
application testing to verify that
3 min read
Article Tags :
Java
java-basics
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like