Skip to main content

Java Fundamentals

User Input

Learning how to get user input in Java helps you make programs that can talk to people. It's like teaching your program to understand what people want, so you can make your programs work better for them.

So far, we've been directly assigning values to variables in our code. But in Java, we can also ask users to input values and then store those values in variables. To do this, we use something called the Scanner class.

Let's take a look at an example together.

import java.util.Scanner;
 
class Main {
    public static void main(String[] args) {
        
        System.out.println("What's your age?");
        
        // steps to take input value
        Scanner input = new Scanner(System.in);
        int age = input.nextInt();
        
        System.out.println("Age is: " + age);
 
        input.close();
    }
}

Don't worry too much about the program just yet.

We'll go through each step of it in this lesson. For now, just run the code.

You'll see a message asking you to "What's your age?". Type in your age and then press the ENTER key.

The program will then show you the age you entered. You'll notice that the output changes depending on the age you input. It's a simple way to get information from users and use it in our programs. We'll dive into each part of the code in more detail soon. But for now, just give it a try and see how it works!

Sample Output

What's your age?
20
Age is: 20

Let's go through the steps in the code for taking input in a simpler way:

  1. Import Scanner class - The first code you will notice here is this import statement at the top of the code.
import java.util.Scanner;

So, This line imports the Scanner class in our program, which helps us take input. It's like getting a special tool ready for use.

You might not be familiar with classes yet, but we'll explore them later in the course. For now, remember that the Scanner class is crucial for gathering input values, and this line of code allows us to employ its capabilities in our program.
  1. Create Scanner class Object - Once we import the Scanner class, we need to create an object of it that we'll use to take the input.
Scanner input = new Scanner(System.in);

Think of it like getting a specific device ready to listen for what the user says.

Again, the concept of object is new to you. Just remember that this code generates an object of the Scanner class. This particular object, named 'input,' is what we'll use to collect input values.
  1. Take user input - Using the Scanner input object along with the . dot operator and nextInt() method to take integer input, we actively gather the user's input. It's like having a conversation where we ask a question, and the user responds, and we listen carefully to what they say. We save their response for later use.
int age = input.nextInt();

The above line takes a value from the user and stores it in the 'age' variable. You don't need to worry with the internal working of this code. Just keep in mind that nextInt() captures integer input, and we use it with the Scanner class object (in our case, 'input').

Before taking the user's input, we displayed the message "What's your age?" to prompt users to provide their age.

  1. Closing the Scanner - After we're done gathering input, we close the Scanner. This is like turning off the "listening device".
input.close();

This is not mandatory. But it is a good practice to use in our code.

Input Types

In the example above, we used the nextInt() method, which is used to read integers. To read other types, look at the table below:

MethodDescription
nextInt()Reads a int value from the user
nextDouble()Reads a double value from the user
nextFloat()Reads a float value from the user
nextBoolean()Reads a boolean value from the user
nextLine()Reads a string value from the user
nextByte()Reads a byte value from the user
nextLong()Reads a long value from the user
nextShort()Reads a short value from the user
There is no nextChar() function is available to read a character. If you want to read a character, we use next().charAt(0). The next() function retrieves the subsequent token/word as a string from the input, while charAt(0) returns the first character of that string. In charAt(NUMBER), the number '0' signifies the index of the word within the string that has been input, assigning that character to the char variable.

Note - Both next() and nextLine() can be used to read string input in Java. The method nextLine() retrieves all the text until the next line break, while next() reads a specific tokenised text based on a designated delimiter, usually whitespace by default. With nextLine(), the scanner's position shifts to the following line after capturing the input, whereas next() keeps the cursor within the same line.

For example:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {

    String sampleText = 
        " I love Java!\n"
      + " You love Java!\n"
      + " User input with Java is so easy!\n"
      + " Just use the Scanner class.\n";

    Scanner scanner = new Scanner(sampleText);

    System.out.println("First nextLine() call : " + scanner.nextLine());
    System.out.println("Second nextLine() call: " + scanner.nextLine());
    System.out.println("First next() call : " + scanner.next());
    System.out.println("Second next() call: " + scanner.next());

    scanner.close();

  }
}

The output is -

First call : I love Java!
Second call: You love Java!
Third call : User
Fourth call: input

As you can see, the function nextLine() reads an entire line of text until the end of the line, while next() extracts one word at a time.

Let's take a look an another example with multiple inputs-

import java.util.Scanner;
 
class Main {
    
    public static void main(String[] args) {
        
        // Create Scanner object.
        Scanner input = new Scanner(System.in);
        
        // Take double input
        System.out.println("Enter a double value:");
        double value = input.nextDouble();
        
        // Take character input
        System.out.println("Enter any character value:");
        char character = input.next().charAt(0);
        
        // Print input values.
        System.out.println("Double Value: " + value);
        System.out.println("Character Value: " + character);
        
        // close the Scanner object
        input.close();
    }
}

Sample output

Enter a double value:
68.34
Enter any character value:
t
Double Value: 68.34
Character Value: t

QUIZ