Wednesday, March 23, 2022

Different ways to read user inputs in Java


  1. Using Scanner
    Scanner in = new Scanner(System.in);
    String name = in.nextLine();
    int number = in.nextInt();
    
  2. Using BufferReader: BufferedReader is synchronous while Scanner is not. BufferedReader should be used if we are working with multiple threads. BufferedReader has a significantly larger buffer memory than Scanner. BufferedReader is a bit faster as compared to scanner because the scanner does the parsing of input data and BufferedReader simply reads a sequence of characters.
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String name = reader.readLine();
    
  3. Using Console: Used to get input from the console. When used this to password, it will not be displayed to the user.
    String name = System.console().readLine();

 

No comments:

Post a Comment