How to take Input in Java Using Scanner Class and BufferedReader Class

We know that a String in java is a collection of characters enclosed in double-quotes. We have learned the concepts of String in Java multiple times and also implemented them in many programs. But usually, we used to pass the String input in the code itself. To develop a console application using Java, it is very important to read input from the user through the console. In this article, we will learn to take the String input from the user after the successful compilation of the Java program. There are many ways to take String input in Java. So let’s start the tutorial on taking String input in Java.

How to take String Input in Java

Taking String Input in Java

Taking string input in Java means taking the String input from the user through the keyboard and then the input values are processed and we get the desired output of the program. There are many utility classes and their methods that enable us to take the String input from the console. We can obtain as many as Strings inputs from the user as required. Let’s look forward to the various methods that take String input from the user.

Techniques to take String Input in Java

The following are some techniques that we can use to take the String input in Java:

1. Using Scanner class nextLine() method
2. Using Scanner class next() method
3. Using BufferedReader class
4. Using Command-line arguments of main() method

1. Using Java Scanner class nextLine() method

The Scanner class is a part of the java.util package in Java. It comes with various methods to take different types of input from users like int, float, double, long, String, etc. The nextLine() method of the Scanner class takes the String input from the user. To use this method we need to import the java.util.Scanner class in our code.

The Scanner class is defined with the InputStream and system.in. We create an object of the Scanner class and pass the predefined object System.in into it. The System.in represents the Standard input Stream that is ready and open to taking the input from the user.

Then using the object of the Scanner class, we call the nextLine() method to read the String input from the user.

The signature of the nextLine() method is:

public String nextLine()

When this method does not find any String input on the console window, it throws NoSuchElementException and also throws IllegalStateException if we close the object of the Scanner class.

So, the general syntax of taking String input using the Scanner class is:

Scanner scannerObject = new Scanner(System.in);
String str = scannerObject.nextLine();

Now, let’s see the example to understand this concept:

Code to take String input using the nextLine() method of Scanner class:

package com.techvidvan.takestringinput;
import java.util.Scanner;
public class ScannerClassMethodDemo {
  public static void main(String[] args) {
    String name,city,course;

    Scanner sc = new Scanner(System. in );
    System.out.println("Welcome to Techvidvan Tutorials");

    System.out.println("Enter your name");
    name = sc.nextLine();

    System.out.println("Enter your city");
    city = sc.nextLine();

    System.out.println("Enter the course that you want to learn from TechVidvan");
    course = sc.nextLine();

    System.out.println("You entered the following details:");
    System.out.println("Name: " + name);
    System.out.println("City: " + city);
    System.out.println("Opted Course: " + course);
  }
}

Output

Enter your name
Avina
Enter your city
Indore
Enter the course that you want to learn from TechVidvan
Java
You entered the following details:
Name: Avina
City: Ujjain
Opted Course: Java

In the above program, during the execution, the console waits after the line-Enter your name until the user enters something.

2. Using the next() method of Scanner class in Java

Java next() method can read the input before space encounters. It cannot read two words separated by space. It retains the cursor in the same line after reading the input.

The signature of next() method is:

public String next()

Next method returns the next complete token from this scanner. It does not accept any parameter and throws NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is in a closed state.

Code to take String input using the next() method of Scanner class:

package com.techvidvan.takestringinput;
import java.util.Scanner;
public class ScannerClassMethodDemo1 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System. in );
    System.out.println("Enter a string:");
    String myStr = sc.next(); //reads string before the space  
    System.out.println("You entered: " + myStr);
  }
}

Output

Enter a string:
Hello, I am learning from TechVidvan Java Tutorial
You entered:
Hello,

So, in the above output, you can see that the output of the next() method is just before the first space encounters.

3. Using Java BufferedReader class

The Bufferedreader class in Java is another predefined class that takes the String input from the user. It reads the text from the console from the character-based input stream. This class is present in the java.io package of Java. The readLine() method of Bufferedreader class reads the String input from the user.

The signature of the readLine() method is:

public String readLine() throws IOException

The readLine() method returns a String containing the contents of the line excluding the line- terminated characters.

To use the BufferedReader class, we need to wrap the predefined object System.in in the InputStreamReader class, then pass this wrapped object to the BufferedReader constructor. Then, finally, we call the readLine method using this object.

So, the general syntax of taking String input using the Bufferedreader class is:

InputStreamReader inputObject = new InputStreamReader(System.in);
Bufferedreader bufferReaderObject = new bufferedReader(inputObject);
String str = bufferReaderObject.readLine();

Code to take String input using the readLine() method of BufferedReader class:

package com.techvidvan.takestringinput;
import java.io. * ;
public class BufferedReaderExample {
  public static void main(String args[]) throws Exception {
    InputStreamReader ir = new InputStreamReader(System. in );
    BufferedReader br = new BufferedReader(ir);
    System.out.println("Enter your name:");
    String name = br.readLine();
    System.out.println("You entered: " + name);
    String sentence;
    System.out.println("Enter a sentence:");
    sentence = br.readLine();
    System.out.println("You entered: " + sentence);
  }
}

Output

Enter your name:
Sneha
You entered: Sneha
Enter a sentence:
This is a Java Tutorial on String input from the user. It is a cool tutorial.
You entered: This is a Java Tutorial on String input from the user. It is a cool tutorial.

Another example of reading data from console until the user writes “Stop”

Let’s see another example when the user keeps entering the String input and can stop giving the input by typing “Stop”. So the data is read and processed until the user enters Stop. Let’s see this example:

Code to understand the concept:

package com.techvidvan.takestringinput;
import java.io. * ;
public class BufferedReaderExample1 {
  public static void main(String args[]) throws Exception {
    InputStreamReader ir = new InputStreamReader(System. in );
    BufferedReader br = new BufferedReader(ir);
    System.out.println("Enter the courses and write Stop when over:");
    String course = " ";
    while (!course.equals("Stop")) {
      System.out.println("Enter Course: ");
      course = br.readLine();
      System.out.println("You entered: " + course);
    }
    br.close();
    ir.close();
  }
}

Output

Enter the courses and write Stop when over:
Enter Course:
Java
You entered: Java
Enter Course:
Python
You entered: Python
Enter Course:
Machine Learning
You entered: Machine Learning
Enter Course:
Artificial Intelligence
You entered: Artificial Intelligence
Enter Course:
Big Data and Hadoop
You entered: Big Data and Hadoop
Enter Course:
Stop
You entered: Stop

4. Using Java Command-Line Arguments of the main() method

Java also provides a way to take String input using the command-line arguments. We need to pass the values while executing the program, i.e., java MyClass arguments-list. So, we enter the command line arguments after the class name. These arguments are passed to the main method of the application through the array of Strings. We can pass any number of arguments through the command-line.

Syntax of passing command-line arguments:

java MyClass argument1 argument3 argumentN

Code to take String input using command-line arguments:

package com.techvidvan.takestringinput;
public class CommandLineStringInput {
  public static void main(String args[]) {
    int iterator = 0;
    for (iterator = 0; iterator < args.length; iterator++) {
      String s = args[iterator];
      System.out.println(s);
    }
  }
}

Output

Take input string in java

Conclusion

Here, we come to the end of the article on taking string input in Java. This concept of Java is one of the most important concepts because it is the most basic thing that you should know. There are many situations when your application becomes dependent on the user’s input, the same is the case when you need to know this concept so that you can easily apply it in your code. We learned the four different techniques to take String input from the user through the console. Two classes Scanner class and the Bufferedreader class are helpful to take user input and Command line arguments are useful in taking the String inputs.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.