Read String from Console in Java
We can use below classes to read input from console.
1. BufferedReader
2. Scanner
Java Read String from Console using BufferedReader
BufferedReader class is from Java IO package. We can use BufferedReader to read text from a character-input stream.
1 2 3 4 5 6 7 8 9 |
public class ConsoleBufferedReader { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Input String:"); String input = br.readLine(); br.close(); System.out.println("Input String = " + input); } } |
Output:
1 2 3 |
Enter Input String: Learning solo Input String= Learning solo |
Java Read from Console using Scanner
If you notice above code, BufferedReader is not flexible and has very limited options. We can only read input data as String. That’s why Scanner class was introduced in Java 1.5 to read from console with many options.
We can use Scanner class to read as String, primitive data types such as int, long etc. We can also read input numbers in different bases such as binary and read it to integer. Let’s have a look at how to use Scanner class to read input data from console.
1 2 3 4 5 6 7 8 9 10 |
public class ReadFromConsoleScanner { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter Input String:"); String input = sc.nextLine(); System.out.println("Input String = " + input); sc.close(); } } |
Output:
1 2 3 |
Enter Input String: Input from console Input String = Input from console |