~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Obtaining Command Line Input in Java

Published on

Updated on

To obtain console input for your program you can use the Scanner class

First import the relevant library

import java.util.Scanner;

Then create a variable to hold the Scanner object

Scanner input;
input = new Scanner(System.in);

Inside the parenthesis, the Scanner binds to the System input which is by default the console

The new varible input now has the ability to obtain input from the console. To do so, use any of the following methods:

Method What it Returns
next() The next space separated string from the console
nextInt() An integer if it exists from the console
nextDouble() A double if it exists from the console
nextFloat() A float if it exists from the console
nextLine() A string up to the next newline character from the console
hasNext() Returns true if there is another token
close() Unbinds the Scanner from the console

Here is an example program where we get the user’s first name

import java.util.Scanner;

public class GetName {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter your name: ");
    String firstName = input.next();
    System.out.println("Your first name is " + firstName); 
  }
}
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter