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:
System.in
: This stream is used for input. It is an instance of theInputStream
class and is typically used with theScanner
class to read input from the user. You can read user input character by character or use utility methods likenextLine()
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 + "!"); } }
System.out
: This stream is used for normal output. It is an instance of thePrintStream
class and is typically used with methods likeprintln()
andprint()
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); } }
System.err
: This stream is used for error output. It is also an instance of thePrintStream
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.