Java Read String from Console

Filed Under: Java

Today we will look into different ways to read string from console in java.

Java Read String from Console

java read string from console
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. Below is a simple program to read string data from console and print it in lower case.


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.


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.


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.

 
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

That’s all for java read from console program or how to read string from console in java.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages