Slide 1
Slide 2
Slide 3

String input in java programming (V25)

No Comments

Methods for Different Types of User Inputs
         The Scanner class provides different methods for different types of user inputs. To find all methods for various user input types, please refer to the table below:

Method Description
1 String next() This method finds and returns the next complete token from this scanner.
2 BigDecimal nextBigDecimal() This method scans the next token of the input as a BigDecimal.
3 BigInteger nextBigInteger() This method scans the next token of the input as a BigInteger.
4 boolean nextBoolean() This method scans the next token of the input into a boolean value and returns that value.
5 byte nextByte() This method scans the next token of the input as a byte.
6 double nextDouble() This method scans the next token of the input as a double.
7 float nextFloat() This method scans the next token of the input as a float.
8 int nextInt() This method scans the next token of the input as an int.
9 String nextLine() This method advances this scanner past the current line and returns the input that was skipped.
10 long nextLong() This method scans the next token of the input as a long.
11 short nextShort() This method scans the next token of the input as a short.

String next() and nextLine()

The next() method in Java provided by the Scanner class is used to read the next word from user input. It reads input until it encounters a whitespace (space, tab, or newline).

The nextLine() method in Java is used to read an entire line of text including spaces from the user input. It is part of the Scanner class and is commonly used to read full input lines in Java.

Syntax:

Source Code:

Copied!
import java.util.Scanner;

public class UserInput {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        // 1. Taking a single word input using next()
        System.out.print("Enter a word: ");
        String word = scanner.next();  // Reads only the first word before space
        System.out.println("You entered (word): " + word);

        // 2. Clear the buffer (useful after nextInt or next())
        scanner.nextLine();  // To consume the leftover newline character

        // 3. Taking a full line input using nextLine()
        System.out.print("Enter a sentence: ");
        String sentence = scanner.nextLine();  // Reads the entire line with spaces
        System.out.println("You entered (sentence): " + sentence);

        // 4. Close the scanner to free resources
        scanner.close();
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top