Java Program to read a character
Overview
To understand keyboard interaction in Java language, let’s write and understand a simple program to read a character from the standard input device, the keyboard.
The stream objects defined in the System class are outlined here:
Program
import java.io.IOException;
/*
* Program to read a single character from the keyboard
* Java Tutorials – www.TestingDocs.com
*/
public class ReadCharacter {
public static void main(String[] args) throws IOException {
System.out.println(“Enter a character from keyboard ::”);
char ch = (char) System.in.read();
System.out.println(“The character entered from the keyboard = ” + ch);
}
}
Program Output
Sample program output:
Enter a character from keyboard ::
q
The character entered from the keyboard = q
The read() method throws IOException. We need to handle the exception type IOException in the program. There are two things to fix the error. We can add the throws declaration clause to the method signature. Handle the code by surrounding it with a try/catch block.
IOException is a subclass of Exception and is a checked exception. It signals that an I/O exception has occurred. This exception is produced by failed or interrupted I/O operations.
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :