Java Stdin and Stdout

Java Stdin and Stdout

Using System.in and System.out in Java

ยท

2 min read

In Java, System.in and System.out are the standard input and standard output streams, respectively. stdin and stdout are fundamental for console-based input and output operations in Java, allowing programs to interact with users and display information.

System.in (stdin):

  • System.in is an instance of the InputStream class that represents the standard input stream.

  • It is used for reading input from the user or from another program.

  • Typically, you use Scanner class or BufferedReader class to read input from System.in.

System.out (stdout):

  • System.out is an instance of the PrintStream class that represents the standard output stream.

  • It is used for writing output to the console.

  • You can use methods like System.out.println() to write data to the standard output stream.

Example:

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();
    scan.nextLine();
    String s = scan.nextLine();
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

Here, we have called scan.nextLine() after getting integer inputs.

If you call the nextLine() method immediately after the nextInt() method, keep in mind that nextInt() reads integer tokens; as a result, the last newline character for that line of integer input is still queued in the input buffer, and the next nextLine() will read the remainder of the integer line (which is empty).

Thanks for reading! ๐Ÿ‘จโ€๐Ÿ’ป

Did you find this article valuable?

Support Dhanush by becoming a sponsor. Any amount is appreciated!

ย