How to read input from console in Java

How to read Console Input in java

There are 3 different ways to read input from console in java. We can read input from console by using any one of the following Class.

Read Console Input using Scanner Class

Possibly this is the most preferred way to read input from console in java because of it’s simplicity and convenient methods like nextInt(), nextByte(), nextFloat(), nextLine() …etc it has to read targeted inputs. Application of this class is not just limited to reading input from console, it can operate on several types of data sources like String, File, InputStream, Readable, ReadableByteChannel and path.

Best thing is that regular expressions can be used to parse and retrieve tokens from input accordingly


  • Convenient methods (nextInt(), nextFloat(), nextByte()) to read primitive data types
  • Regular expressions can be used to read custom patterns.


Scanner class is not safe for multithreaded use since reading methods are not synchronized.

This Class is available to import at java.util.Scanner

Where is Standard input stream which is by default console

Read Console Input using BufferedReader Class

This method was introduced in the JDK 1.0. This is relatively the complex way to read input compared to Scanner class. We have to use Both BufferedReader and InputStreamReader combined to read input from console. You can trade off this little complexity with efficiency.


This method of reading console input using BufferedReader is efficient.


Relatively complex code compared to other methods

Following Classes are required to import

Read Console Input Using Console Class

The class Console was introduced in java 1.6. It is preferred way, if you plan to read secrets or passwords from command line since it provides the way to mask input through method readPassword(). Console class methods allow you to pass string for prompt as well which supports string formatting syntax. So you can use format specifiers like %s and %d in the format string.


  • Read password or secret phrases without echoing the entered characters on to console
  • Read and write operations are synchronized
  • String formatting can be used


  • It doesn’t work in non-interactive environments like IDE and jshell

Here is the complete code which demonstrates reading input from console by using above mentioned 3 ways

How to interact with the clipboard using JavaScript

Clipboard - Copy, Cut and Paste Using JavaScript

It’s never been a easier job to copy the text programmatically with in the browser. We use to rely on flash to get it done. Good news, now we have more than couple of ways to interact with clipboard using JavaScript.

Clipboard is a data buffer which is used to store the data for a short-period of time to perform operations like cut, copy and paste. Here are the ways that you can choose to operate with clipboard for cut, copy and paste operations.

Interact with clipboard using document.execCommand

document.execCommand API allows us to run commands on editable regions like form inputs and contenteditable elements. Visit commands of document.execCommand to find out all supported commands. We would use commands “copy”, “cut” and “paste” to interact with system clipboard.

document.execCommand is an old API compared to Async Clipboard API yet supported by most browsers.

Using document.execCommand for cut, copy & paste operation is limited to copying the selected text only

All document.execCommand calls must take place inside short-living event handlers of user actions like mouse click, keypress etc. Any kind of special permission is not required if document.execCommand is executed inside event handlers(as a result of user action, ex: mouse click). If it is called outside the event handlers, behavior depends on browser implementation, on Firefox this command will not execute and you will see error in the console

document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.

Copying text of given element using command.execCommand

Let’s see how to copy textContent of a given element using command.execCommand

function copyContent(elementID) {
const ele = document.getElementById(elementID);;

// Assume id of button is copy and id of input element is input
document.querySelector("#copy").addEventListener("click", e => copyContent("input"))

As you can see above code, we have selected content of given element first then called document.execCommand(‘copy’) to copy followed by blur to deselect text.

Cut content from input or contentEditable elements

Process is same as copy but pass “cut” as an argument instead of “copy” to document.execCommand function call.

function cutContent(elementID) {
const ele = document.getElementById(elementID);;

// Assume id of button is cut and id of input element is input
document.querySelector("#cut").addEventListener("click", e => cutContent("input"))

The paste command document.execCommand(‘paste’) is not supported by most of the browsers because of possible security concerns

See the Pen Clipboard document.execCommand by neotam (@neotam) on CodePen.

Copy text to clipboard using document.execCommand

If you want to put some random text into clipboard instead of selected content of the element, you have to create a temporary element, append it to document body, select it and then execute copy command. Since document.execCommand(‘copy’) only copies selected text /nodes from the DOM.

function copyToClipboard(text){
const ele = document.createElement('textarea');
ele.value = text;
ele.setAttribute('readonly', true)
// Following styling is to avoid flashing textarea on screen = 'absolute'; = 0; = 'transparent'; = 'none'; = '-100%';
const textToCopy = "Hello! I got Copied";
document.getElementById('copy').addEventListener('click', e => copyToClipboard(textToCopy))

See the Pen clipboard document.execCommand copyToClipboard by neotam (@neotam) on CodePen.

Asynchronous Clipboard API

This is recent addition to the specification, which seems more matured. Async clipboard API provides asynchronous access to the clipboard to read and write text directly so called Async Clipboard API . Unlike document.execCommand this one need permissions to interact with clipboard

This Clipboard (Async Clipboard API) only works in secure context, i.e only on HTTPS

Navigator exposes the system clipboard through property Navigator.clipboard

All methods of Clipboard or navigator.clipboard returns Promise . Which will be resolved if operation on clipboard is successful else it will rejected if there is any kind of error or clipboard access is denied because of permissions.

Following are PermissionNames related to Async Clipboard API, which are passed to navigator.permissions.query to request or check the permission.

  • clipboard-write
  • clipboard-read

Write to clipboard using navigator.clipboard

Clipboard has following two method to write data/text into clipboard

  • write()
  • writeText()

These methods trigger asynchronous operation and returns Promise which will be resolved on success else rejected on failure(possible if access denied)

Following simple function demonstrates using of navigator.clipboard which takes text and writes into the clipboard.

function writeToClipboard(text) {
result => {
console.log("Successfully copied to clipboard", result)
err => {
console.log("Error! could not copy text", err)

You can use the above function directly or you can wrap another function around it which tests for (permissions)access before calling this function

Checkout above code in action at write to clipboard using Async Clipboard API

Read from clipboard using navigator.clipboard

navigator.clipboard(Clipboard) has following two methods which are used for reading data/text from clipboard

  • read
  • readText

This following function uses navigator.clipboard.readText to read copied text from clipboard. Browser might prompt the user for permission to grant access to clipboard to read text.

Clipboard Events

We can listen for the “copy”, “cut” and “paste” events on document to override what is being copied and what is being pasted. This is useful when you want to apply formatting(or filter) to text while it goes to clipboard or comes out of clipboard

Override the copy event

document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', 'Hello! Welcome');
e.clipboardData.setData('text/html', '<b>Hello, Its copy override!</b>');

Override the cut event

document.addEventListener('cut', function(e) {

e.clipboardData.setData('text/plain', 'Hello! Welcome');
e.clipboardData.setData('text/html', '<b>Hello, Its copy override!</b>');

//Since we are overriding cut operation and preventing default we need
// to manullay remove the selecte text

Override the paste event

document.addEventListener('paste', function(e) {
if (e.clipboardData.types.indexOf('text/html') > -1) {
var oldData = e.clipboardData.getData('text/html');
var newData = '<b>Oh Yeah!</b> ' + oldData;

To prevent user from performing copy, cut and paste operation on particular element. Add “return false” to event handlers on that corresponding element.

<div oncopy="return false" oncut="return false" onpaste="return false"> </div>

Clipboard Library

If you are a library freak and don’t mind using Vanilla JavaScript . Here is the clipboard library for you

Install Javascript clipboard library using npm

npm install clipboard --save 

How to use this library is out of scope of this article. I will leave it to you, you may find more if you head over to npm clipboard