Techoceanhub logo

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.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .