Java is a versatile programming language with advanced features such as threads, design patterns, annotations, Lambda expressions, etc. In programming languages, taking user input is a crucial skill as it builds the bridge between the application and the user.
Among the various data types supported by Java, string is most commonly used by developers. This is due to its flexibility and ability to store large amounts of data. Using the Scanner class is a common practice of taking string input from the user in Java. However, there are several different methods for taking string input that are discussed in this article.
This article covers all possible aspects of taking string input in Java.
How to Input a String in Java?
There are different classes to take and manipulate the string input in Java. These classes include Scanner, BufferReader, and Console class. To receive input, multiple built-in methods are invoked by creating instances of these classes.
To input a string in Java, explore these methods:
- Using Scanner Class
- Using BufferedReader Class
- Using Console Class
- Using Command Line args
- Input a String Using Scanner Class
The Scanner class from the “java.util” package is commonly used for reading input from different sources. It is a versatile and powerful class that extends support for multiple data types such as string, boolean, float, double, etc.
The common syntax for importing the Scanner class in Java is as follows:
import java.util.Scanner;
The two most common functions for manipulating the strings are the “next()” and “nextLine()” methods. Have a look at the implementation of these methods for taking the string input from the user:
Method 1: Using next()
The next() method from the Scanner class reads the input until it encounters a whitespace or line termination characters. After importing the “java.util” package from the Scanner class, a Scanner object “scanObj” is created that accepts the standard input.
The input string that is provided by the user is read by the next() method and is stored in the string variable “input”. The variable’s value “input” is then printed as shown below:
Scanner scanObj=new Scanner(System.in);
System.out.println("Enter a string");
String input= scanObj.next();
System.out.println("String is : " + input);
Complete Code & Output
Method 2: Using nextLine()
The “nextLine()” method reads a single line of text from the input sources. This method reads every character of the string, including any whitespaces. The output is returned when the end of the line is reached or it encounters the newline characters (“\n”).
After importing the “java.util” package, the Scanner object “scanObj” is created and the nextLine() method is invoked using this instance. The string input by the user is stored in the variable “input” which is of string data type. The value is then printed via the print statement:
Scanner scanObj=new Scanner(System.in);
System.out.println("Enter a string");
String input= scanObj.nextLine();
System.out.println("String is : " + input);
Complete Code & Output
Method 3: Using the hasNext()
The Scanner class in Java divides the input into tokens and then reads it via different input methods. Similarly, the hasNext() method of the Scanner class determines if there are any tokens for reading in the input. It returns a boolean output i.e., true or false.
Let’s demonstrate the practical application of using the hasNext() to take a string input.
The Scanner object “input” accepts the standard input (via the keyboard) after including the Scanner class from the “java.util” package. The user is prompted to enter a string via the print statement:
Scanner input=new Scanner(System.in);
System.out.println("Enter string");
The while loop checks the data for reading by using the hasNext() method. Inside the loop, the input provided by the user is read by the next() method and is stored in the str variable. The value of “str” is then printed. The loop terminates when there are no more tokens in the input for reading:
while(input.hasNext())
{
String str=input.next();
System.out.println(str);
}
Complete Code & Output
Method 4: Using forEachRemaining() (For Multiple Strings)
The forEachRemaining() method traverses each element and performs the specified action on them (Introduced in Java 8). This method is part of the Java Spliterator Interface and has no return type.
The java.util package is imported to include all the essential classes and dependencies such as Scanner for taking user input. After that, the Scanner class object “input” invokes the forEachRemaining() method that iterates through each string provided by the user. The multiple strings provided by the user are then printed:
Scanner input = new Scanner(System.in); // creates a scanner object
System.out.println("Enter different String "); //prompt the user to enter a string
input.forEachRemaining(System.out::println);
Complete Code & Output
Method 5: Using Lambda Expressions
Lambda expression was introduced in Java 8 which provides an easy and concise way for writing codes. Such expressions follow the functional interface and return the values after processing. Lambda expressions work similarly to the methods. However, unlike methods, lambda expressions are nameless and are directly declared and used within the body of other methods.
Let’s implement the Lambda expressions to take multiple-string input from the user. For this, import the Scanner class for the java.utils package. Then, the Scanner object “input” is created and the user is prompted to enter a string:
Scanner input = new Scanner(System.in); // creates a scanner object System.out.println("Enter different String "); // prompt the user to enter a string
The scanner object “input” invokes the forEachRemaining() method to iterate over each character of the string. In this code, the “strInput -> System.out.println()” is a lambda expression that continues to accept multiple string input from the user and display it:
input.forEachRemaining(strInput -> System.out.println("Input Entry : " + strInput));
Complete Code & Output
- Input a String Using BufferedReader Class
The BufferedReader class is more efficient and effective for taking larger streams of character-based string input. It uses the buffering mechanism which makes it more flexible than the Scanner class for working with the strings.
The BufferedReader, IOException, and InputStreamReader classes are provided by the java.io package which is imported as below:
import java.io.*;
Inside the try block, the “buffer” object of the “BufferedReader” class is created with the InputStreamReader object. It is used to read data in the form of bytes and then convert it into the specified characters. The readLine() method reads the string input that is invoked by the “buffer” object. Finally, it is stored and displayed.
The catch block displays the exception that may occur during the execution of the code:
try {
BufferedReader buffer =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string");
String str=buffer.readLine();
System.out.println("The input is : " + "\"" + str +"\"");
}
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
- Input a String Using Console Class
The Java Console class is used for Console-based applications. It is simple to use and provides built-in methods for input and output functionalities. It handles the read and operations via the terminal but it is not as versatile as the Scanner class.
There are two variants of the Console class in Java. The basic syntax of the Console class is as follows:
public String readLine()
For using the Console, first, import it in the code via the following line of code:
import java.io.Console;
An instance of the Console class “console” is created that invokes the readLine() method. The readLine() method reads one line of data and stores it in the str variable which is then printed:
Console console=System.console();
System.out.println("Enter a string");
String str=console.readLine();
System.out.println("The string is " + "\"" +str + "\"" );
Complete Code
Output
Inside the project directory, locate the “src” folder. Open CMD and provide the following command to the terminal after replacing the placeholder “<JavaFileName>”:
java <JavaFileName>
The output is as follows:
Using the Formatted String in the Console Class
Another variant of the Console class accepts character-based input streams with different string formats. The basic syntax is as follows:
public String readLine(String format, Object.. args)
To use this, first import the Console class from the java.io package inside the code:
import java.io.Console;
The string variable “input” stores the single line read by the readLine() method of the Console class. The “%S” specifies the string format and capitalizes the given string i.e., “enter string”. The value of the input variable is then printed:
String input=System.console().readLine("%S","enter string");
System.out.println("Output is " + "\"" + input +"\"");
Complete Code
Output
Inside the “src” folder of the Java project directory, open CMD. Replace the placeholder “<JavaFileName>” with your code file name and provide the following command to the terminal:
java <JavaFileName>
The output is as follows:
- Input a String Using Command Line args
The command line arguments in Java are those arguments that are passed at the time of execution of the code. Such arguments provide a flexible way of handling the data via the Console. However, the only drawback is that the command line args accepts the input only once while the programming is running.
The “String args []” in the main() method are known as default arguments that are used for taking runtime input. Let’s use the Command-line args to take string input by the user.
Inside the main method, the for loop is used to accept the string input of dynamic length. The args[i] inputs a string which is then stored “str”. The value of the variable is then displayed on the console: In the header of the main() method, the String args[] are the default arguments:
for (int i = 0; i < args.length; i++)
{
String str = args[i];
System.out.print(str+" ");
}
Output
To execute the code file, navigate to the “src” folder of the project directory and open CMD. Provide the following command to the terminal after replacing the placeholder “<JavaFileName>” with your file’s name:
java <JavaFileName>
The output is as follows:
That is all from this guide.
Conclusion
In Java, the string data types are used to accept character-based input from different sources. To input a string in Java, use the built-in methods of the Scanner, Console, or BufferedReader class or provide the input via the Command-Line args.
The Scanner class is easy to use but does not support large string inputs. The BufferedReader class handles huge volumes of data efficiently but requires libraries for normal functioning. The Console class is simple but does not provide flexibility and interactivity to the code.
This article has discussed and implemented various methods to take string input in Java.