How to take String Input in Java

Amansingh Javatpoint
2 min readMay 29, 2021

--

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to take String input in Java:

1) By Using Java Scanner class

2) By Using Java BufferedReader class

3) By Using the Command Line argument

By Using Java Scanner class

The Scanner class is defined in java.util package that is used to take input from the user. The Scanner class provides the following two methods to take input from the user.

  1. Scanner.nextLine() Method
  2. Scanner.next() Method

Let’s discuss each of the mentioned methods to take input from the user.

  1. Scanner.nextLine() Method

The nextLine() method reads the input till the line gets terminated and shifts the cursor to the next line. The syntax of the nextLine() method is:

Syntax:

public String nextLine()

The method does not accept any parameter. It returns the string that was skipped. If the method finds no line to read, the method throws the NoSuchElementException.

FileName: StringInputExample.java

// importing the Scanner class

import java.util.Scanner;

public class StringInputExample

{

// main method

public static void main(String argvs[])

{

// To hold the string input by the user

String str;

// creating an object of the Scanner class

Scanner scnr = new Scanner(System.in);

System.out.print(“Enter a string: “); // invoking the method nextLine()

// to take input from the user

str = scnr.nextLine();

// for new line

System.out.println();

// displaying the entered string

System.out.print(“The string entered by the user is: “ + str );

}

}

--

--

No responses yet