Skip to content

Commit 7a38286

Browse files
committed
feat: demonstrate console input using System.in.read() (Demo3)
WHAT: - Implemented a simple program that reads a single byte from the console using `System.in.read()`. - Casts the byte value to a character and prints it. HOW IT WORKS: 1. `System.in` is a standard input stream connected to the keyboard. 2. `System.in.read()`: - Reads a single byte of input as an `int` (0–255). - Returns -1 if the end of the stream is reached. 3. The read byte is cast into a `char` to display the entered character. 4. Exceptions (e.g., I/O errors) are caught using a try-catch block. KEY POINTS: - Only reads **one character** at a time (first byte of input). - If you type a character and press Enter, it captures the ASCII code of the first character, while the Enter key may remain in the buffer. - To read full lines or strings, classes like `BufferedReader` or `Scanner` are more practical. REAL-WORLD USE CASES: - Learning low-level I/O operations in Java. - Useful for understanding how streams work before moving to higher-level input handling. - Could be applied in simple console-based utilities where byte-level input is sufficient. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7c49837 commit 7a38286

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed
Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
import java.io.IOException;
2+
23
class Demo3 {
3-
public static void main(String[] args)
4-
{
5-
try
6-
{
4+
public static void main(String[] args) {
5+
try {
76
int x = System.in.read();
87
System.out.println( (char)x);
98
}
10-
catch (IOException e)
11-
{
9+
catch (IOException e) {
1210
System.out.println(e);
1311
}
1412
}
1513
}
14+
1615
/*
1716
This program reads one character from the keyboard input (System.in.read()) and prints it.
1817
It captures any input/output exceptions that might occur during reading.
1918
2019
Basically, it waits for you to press a key and then shows that character.
21-
*/
20+
*/

0 commit comments

Comments
 (0)