×

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

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 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.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.