Last Updated:

Reading from the console in Java

Method 1: Read from the console using System.in.read

 

The easiest way to read data from the console is through the System.in.read() method. This method allows you to read data one by one code. This is a blocking method, that is, by calling it, the program will continue to execute only when any symbol is entered into the console:

int code = System. in. read();

char c = (char) code;

System. out. println("You entered: " + c + ", character code: " + code);

 

This is a very easy way to read from the console and there are more convenient ways to read.

Method 2: Read from the console using Scanner

 

The java.util.Scanner class provides several convenient methods for reading from the console:

  • hasNextInt() – will return true if it is currently possible to subtract an integer from the console
  • nextInt() – subtracts an integer from the console
  • hasNextDouble() – will return true if it is currently possible to subtract a double number from the console
  • nextDouble() – subtracts a real number from the console
  • hasNextLine() – will return true if any characters can be read from the console
  • nextLine() – reads a string from the console

All of these methods are blocking.

In this example, we check if an integer is available in the console and, if so, output it to the console again:

 

 
Scanner scanner = new Scanner(System. in);
System. out. print("Enter an integer: ");
if (scanner. hasNextInt()) {
int i = scanner. nextInt();
System. out. println(i);

else 
{
System. out. println("You did not enter an integer");
}
 

Similarly, the hasNextDouble()/nextDouble() methods for real numbers and the hasNextLine()/nextLine() methods for strings are used.

Conclusion

 

In this article, we figured out how to read data from a standard output stream. Now you know how to subtract numbers, symbols, and strings from the console.

Source code

 

 
readfromconsolein.java
readfromconsolescanner.java
import java. io. IOException;

public class ReadFromConsoleIn {
public static void main(String[] args) throws IOException {
int code = System. in. read();
char c = (char)code;
System. out. println("You entered: " + c + ", character code: " + code);
}
}