×

How to take String Input in Java

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 );
}
} 

Output:

String Input in Java 1

Explanation: After displaying the message Enter a string, the cursor waits on the console for the user to enter string. The method nextLine() reads till the user hits enter and return the read stuff, which is captured by the variable str. The same read string is shown in the output. Note that hitting the enter button shows that the line has been terminated.

Scanner.next() Method

The next() method reads the input till the line gets terminated or white space is encountered. The main difference between the nextLine() and next() method is that the latter one terminates when white space is encountered, where the former one terminates only when enter is pressed. The syntax of the next() method is:

Syntax:

public String next()

Returns:

The read line is returned.

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: StringInputExample1.java

 // importing the Scanner class
import java.util.Scanner;
public class StringInputExample1
{ 
// main method
public static void main(String argvs[])
{
// To hold the string input by the user
String str;
// Instantiating the Scanner class by creating its object
Scanner scnnr = new Scanner(System.in); 
System.out.print("Enter a string: ");
// invoking the method next()
// to take input from the user
str = scnnr.next();
// for new line
System.out.println();
// displaying the entered string
System.out.print("The string entered by the user is: " + str );
}
} 

Output:

String Input in Java 1

Explanation: The user enters My Name is Khan. However, after the word “My” white space is encountered. Hence, the rest three words are not read, and the same can be confirmed by observing the output.

By using Java BufferedReader Class

Java BufferedReader Class is used to read the stream of characters. The class accepts an object of the InputStreamReader class. So, it is necessary to create a constructor of the InputStreamReader class and pass its object to the BufferedReader class as a parameter. The BufferedReader class has the readLine() method to take input from a user. The readLine() method reads one line at a time.

Syntax:

public String readLine()

It returns the line entered by the user. It does not include any line-termination characters, or null if the end of the stream has been reached.

Let’s observe the following program to understand how the BufferedReader class is used for taking input from the user.

FileName: StringInputExample2.java

 // Import statements
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringInputExample2
{ 
// main method
public static void main(String argvs[]) throws IOException
{
String str;
// Creating an object of the InputStreamReader class
InputStreamReader inputStrObj = new InputStreamReader(System.in);
// Creating an object of the BufferedReader class
BufferedReader bufrObj = new BufferedReader(inputStrObj);
System.out.print("Enter a string: ");
// invoking the method readLine()
// to take input from the user
str = bufrObj.readLine();
// for new line
System.out.println();
// displaying the entered string
System.out.print("The string entered by the user is: " + str );
}
} 

Output:

String Input in Java 1

Explanation: In the constructor of the InputStreamReader class, System.in is passed. It is done because the input is being taken from the keyboard. With the help of InputStreamReader class, the BufferedReader class stores the input given by the user through keyboard.

By using the Command Line Argument

Command Line argument is present in the main method (String argvs[]). String argvs[] is a string array that accepts a line as an input. Let’s understand the usage of command-line argument with the help of the following Java program.

FileName: StringInputExample3.java

 public class StringInputExample3
{ 
// main method
public static void main(String argvs[])
{
// To store the elements of the String array argvs
String str = "";
// Calculating the size of the String array
int size = argvs.length;
// loop for iterating over the elements of the String array argvs
for(int i = 0; i < size; i++)
{
    // Converting the String array into a string
    str = str + argvs[i] + " ";
}
// displaying the entered string
System.out.print("The string entered by the user is: " + str );
}
} 

Output:

String Input in Java 1

Explanation: The command line argument is put when the program is executed using the java command. The number of elements in the String array argvs[] is decided by the white spaces present in the input string. In the input string (“My name is Khan”), there are three white spaces present. Hence, there are four string elements present in the array argvs (“My”, “name”, “is”, “Khan”). The array argvs is then parsed using the for-loop, and elements of the array argvs are then concatenated to build the string again, as we have shown in the above output.


Related Topics

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.