Search code examples
consolejava.util.scannerbufferedreaderjava-6java-5

When should we use console class?


I was reading about Console class, and in the very first line, it was written

New to Java 6 and when we are running Java SE 6 from command line, then we are typically using console class object

So, which means we are implicitly using console class through the command line ??

Then, I started looking for more detail about Console class and I found Input from console class in java and Console link. So, concluded some points

  1. Console class are only usable outside the IDE using System.console().readLine();
  2. Console class reads a password or passphrase from the console with echoing disabled using readPassword()

Although, we had Scanner class and BufferedReader class to read the input from console and that was added earlier than Java 5. So, only due to security reason Console class was added in Java 6 ? or are there any other advantage(s) to use this class.

Could anyone share more details about Console class ?


Solution

  • The Console class reads directly from the process console (usually /dev/console in Unix systems). The console differs from System.in in that it cannot be redirected when a command is launched. It is also used to read passwords because reading from the console you can control whether or not you echo the chars being typed.

    To clarify more on this class, read about console and standard input in Unix systems (this is typically a Unix thing and I'm not really sure how it maps to Windows systems).

    Finally, Scanner can read from any input: a file, an stream, or the console itself so it's different from Console.