In this tutorial, we will learn how to take String input in Java. There are two ways you can take string as an input from user, using Scanner class and using BufferedReader. However most common way is using Scanner class. Let’s see programs of each of these approaches:
1. String Input using Scanner Class
In this example, we are using nextLine()
method of Scanner class to read the user input. This way we can read the entire line entered by user. Don’t forget to import java.util.Scanner
package to use Scanner class.
import java.util.Scanner;
public class StringInputExample {
public static void main(String[] args) {
// Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Prompt user for string input
System.out.println("Enter a string:");
// Read the user input using nextLine() method
String input = scanner.nextLine();
// Print the input string
System.out.println("User entered: " + input);
// Close the Scanner object after use
scanner.close();
}
}
Notes:
- Scanner: The
Scanner
class is part of thejava.util
package and it contains various methods that can be used to read user inputs. - nextLine(): This method of Scanner class reads the entire line entered by user including spaces until the end of the line.
- Closing the Scanner: The
close()
method of Scanner class is used to close the Scanner after use to prevent resource leaks. Although, the program runs fine without using this method, it is still recommended to use this as part of best practices.
2. String Input using BufferedReader
Another way to read String input in Java is by using BufferedReader
. This is less common but still useful in some cases.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class StringInputExample {
public static void main(String[] args) {
// Create a BufferedReader object
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Prompt user for string input
System.out.println("Enter a string:");
try {
// Read user input
String input = reader.readLine();
// print user entered string
System.out.println("You entered: " + input);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Leave a Reply