How can we read from standard input in Java?


The standard input(stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings. To read any data from a keyboard, we can use either a Reader class or Scanner class.

Example1

import java.io.*;
public class ReadDataFromInput {
   public static void main (String[] args) {
      int firstNum, secondNum, result;
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      try {
         System.out.println("Enter a first number:");
         firstNum = Integer.parseInt(br.readLine());
         System.out.println("Enter a second number:");
         secondNum = Integer.parseInt(br.readLine());
         result = firstNum * secondNum;
         System.out.println("The Result is: " + result);
      } catch (IOException ioe) {
         System.out.println(ioe);
      }
   }
}

Output

Enter a first number:
15
Enter a second number:
20
The Result is: 300


Example2

import java.util.*;
public class ReadDataFromScanner {
   public static void main (String[] args) {
      int firstNum, secondNum, result;
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter a first number:");
      firstNum = Integer.parseInt(scanner.nextLine());
      System.out.println("Enter a second number:");
      secondNum = Integer.parseInt(scanner.nextLine());
      result = firstNum * secondNum;
      System.out.println("The Result is: " + result);
   }
}

Output

Enter a first number:
20
Enter a second number:
25
The Result is: 500

Updated on: 22-Oct-2023

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements