Read Keyboard Input: Java


This video tutorial shows how to read user input from Keyboard in Java.

In this tutorial we illustrate using a relatively simple program, where user is asked to input some string and it is read by the program and then out put to the console window. Simple java program.

Import
We have to import io package, so that we can make use of DataInputStream Class present in io package.

    import java.io.*;

Creating Object
Next, we create an object of the inbuilt class DataInputStream. And not that it takes a parameter System.in for reading keyboard inputs.

DataInputStream d = new DataInputStream(System.in);

try catch
To know more about try catch and finally read: Try, Catch and Finally in Java.

Since user can give any kind of unwanted input, we should write those code (which may rise exception) inside the try block.
and write the corresponding catch statement.

try
{
System.out.println("Entered String is: "+d.readLine());
}
catch(Exception e)
{
System.out.println(e);
}

Video Tutorial: Read Keyboard Input: Java


[youtube https://www.youtube.com/watch?v=FzUOZo3AX2Y]

YouTube Link: https://www.youtube.com/watch?v=FzUOZo3AX2Y [Watch the Video In Full Screen.]




Full Source Code:(keyboardInput.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.*;
 
class keyboardInput
{
public static void main(String args[])
{
DataInputStream d = new DataInputStream(System.in);
 
System.out.println("Enter a string");
try
{
System.out.println("Entered String is: "+d.readLine());
}
catch(Exception e)
{
System.out.println(e);
}
 
}
}

Output:
Enter a string
Microsoft Windows 8
Entered String is: Microsoft Windows 8

Leave a Reply

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