In this Java tutorial, you will learn how to read a string from console input entered by user using Scanner class, with examples.
Java – Read String from Console
To read a string from Console as input in Java applications, you can use Scanner class along with the InputStream, System.in.
When you are developing console applications using Java, it is very important that you read input from user through console.
In this tutorial, we will learn how to prompt user to input a string and then read the string from console input.
Examples
1. Read string from console input
In this example, we shall define a Scanner with the input stream, System.in.
System.in creates a standard input stream which is already open and ready to supply input data.
Scanner is simple text scanner which can parse primitive types and strings using regular expressions.
So, passing System.in to Scanner allows us to parse or read string from standard input stream, which is console.
Example.java
import java.util.Scanner;
/**
* An example program to read a String from console input in Java
*/
public class Example {
public static void main(String[] args) {
System.out.print("Enter a string : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
System.out.println("String read from console is : \n"+inputString);
}
}
When the program is run, the execution waits after printing the prompt string "Enter a string : "
, where the user would enter a string something like "hello world"
as shown in the following console window.
The program prints the string read from the console input in the next step. The whole output in the console would be as shown in the following.
Output
Enter a string : hello world
String read from console is :
hello world
About System.in
In the context of reading something from the console, System class provides a means to access standard input through one of its fields, in.
in
field is a Stream (to be specific, its a InputStream), which is declared public static and final. Hence, one can use in
directly without any initialization.
Typically, this InputStream corresponds to keyboard input or another input source specified by the host environment or user.
Conclusion
In this Java Tutorial, we have learned to use Scanner class to read a String from console input in Java.