Java Read String from Console
We can use below classes to read input from console.
- BufferedReader
- 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. Below is a simple program to read string data from console and print it in lower case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.journaldev.examples; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaReadFromConsoleBufferedReader { 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 in Lower Case = " + new String(input).toLowerCase()); } } |
Below is the output produced by one sample run of above program.
1 2 3 4 5 |
Enter Input String: Java Developer Input String in Lower Case = java developer |
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 11 12 13 14 15 16 |
package com.journaldev.examples; import java.util.Scanner; public class JavaReadStringFromConsoleScanner { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a String:"); String input = sc.nextLine(); System.out.println("Input String in Upper Case = " + input.toUpperCase()); System.out.println("Please enter a integer in Binary Format:"); int i = sc.nextInt(2); System.out.println("Number in Decimal = " + i); sc.close(); } } |
Below is the output produced by above program when executed and input is provided in Console.
1 2 3 4 5 6 7 8 |
<span style="color: #008000;"><strong><code> Please enter a String: Java Read String using Scanner Class Input String in Upper Case = JAVA READ STRING USING SCANNER CLASS Please enter a integer in Binary Format: 110110 Number in Decimal = 54 </code></strong></span> |
That’s all for java read from console program or how to read string from console in java.