T E C h O C E A N H U B

Standard I/O streams (System.in, System.out, System.err)

In Java, the standard input/output (I/O) streams are represented by the objects System.in, System.out, and System.err. These streams are associated with the console or terminal where your Java program is running and allow you to read input from the user and write output to the console.

Here’s a brief explanation of each standard I/O stream:

  1. System.in: This stream is used for input. It is an instance of the InputStream class and is typically used with the Scanner class to read input from the user. You can read user input character by character or use utility methods like nextLine() to read entire lines of text.

Example usage:

import java.util.Scanner;

public class ReadInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}
  1. System.out: This stream is used for normal output. It is an instance of the PrintStream class and is typically used with methods like println() and print() to display output on the console. By default, the output is directed to the console.

Example usage:

public class OutputExample {
    public static void main(String[] args) {
        System.out.println("This is a sample output.");
        int num = 42;
        System.out.println("The number is: " + num);
    }
}
  1. System.err: This stream is used for error output. It is also an instance of the PrintStream class and is typically used to display error messages or diagnostic information on the console. By default, the error output is also directed to the console.

Example usage:

public class ErrorOutputExample {
    public static void main(String[] args) {
        System.err.println("An error occurred!");
        System.err.println("Please check your input.");
    }
}

It’s important to note that you can redirect these streams to other destinations, such as files, by using the appropriate methods provided by the System class. However, the default behavior is to use the console for input and output operations.

Copyright ©TechOceanhub All Rights Reserved.