Different Ways to Take Input from User in Java

There are mainly five different ways to take input from user in java using keyboard.

1. Command Line Arguments

2. BufferedReader and InputStreamReader Class

3. DataInputStream Class

4. Console Class

5. Scanner Class

 

Below I have shared example for each of them.

 

Different Ways to Take Input from User in Java

 

How to Take Input from User in Java

Command Line Arguments

It is one of the simplest way to read values from user. It will work only when you are running the program from command line.

class CLAExample
{
	public static void main(String...s)
	{
		System.out.println(s[0]+" "+s[1]);
	}
}

 

BufferedReader and InputStreamReader Class

import java.io.BufferedReader;
import java.io.InputStreamReader;

class BufferedReaderExample {
	public static void main(String...s) throws Exception{
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);

		System.out.println("Enter a value:");
		String str = br.readLine();
		System.out.println(str);
	}
}

 

DataInputStream Class

import java.io.DataInputStream;

class DataInputStreamExample {
	public static void main(String...s) throws Exception{
		DataInputStream dis = new DataInputStream(System.in);
		System.out.println("Enter a value:");
		String str = dis.readLine();
		System.out.println(str);
	}
}

 

Console Class

It will work only when you are running the program from command line.

import java.io.Console;

class ConsoleExample {
	public static void main(String...s){
		Console c = System.console();
		System.out.println("Enter a value:");
		String str = c.readLine();
		System.out.println(str);
	}
}

 

Scanner Class

One of the most commonly used way to read from keyboard.

import java.util.Scanner;

class ScannerExample {
	public static void main(String...s){
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a value:");
		String str = sc.nextLine();
		System.out.println(str);
	}
}

 

You can ask your queries in comment section.

Happy Coding!! 🙂 🙂

Leave a Comment

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