- Java System.in, System.out, and System.error
- System.in
- System.out
- System.err
- Simple System.out + System.err Example:
- Exchanging System Streams
- Exit codes in Java – System.exit() method
- 1. Zero
- 2. Non-Zero
- Java System.in, System.out, and System.error
- System.in
- System.out
- System.err
- Simple System.out + System.err Example:
- Exchanging System Streams
- System.exit(). Какой код выхода использовать?
- Java system error code
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Java System.in, System.out, and System.error
Java has 3 streams called System.in, System.out, and System.err which are commonly used to provide input to, and output from Java applications. Most commonly used is probably System.out for writing output to the console from console programs (command line applications).
System.in, System.out and System.err are initialized by the Java runtime when a Java VM starts up, so you don’t have to instantiate any streams yourself (although you can exchange them at runtime). I will explain each of these streams in deeper detail later in this tutorial.
System.in
System.in is an InputStream which is typically connected to keyboard input of console programs. In other words, if you start a Java application from the command line, and you type something on the keyboard while the CLI console (or terminal) has focus, the keyboard input can typically be read via System.in from inside that Java application. However, it is only keyboard input directed to that Java application (the console / terminnal that started the application) which can be read via System.in. Keyboard input for other applications cannot be read via System.in .
System.in is not used as often since data is commonly passed to a command line Java application via command line arguments, files, or possibly via network connections if the application is designed for that. In applications with GUI the input to the application is given via the GUI. This is a separate input mechanism from System.in.
System.out
System.out is a PrintStream to which you can write characters. System.out normally outputs the data you write to it to the CLI console / terminal. System.out is often used from console-only programs like command line tools as a way to display the result of their execution to the user. This is also often used to print debug statements of from a program (though it may arguably not be the best way to get debug info out of a program).
System.err
System.err is a PrintStream . System.err works like System.out except it is normally only used to output error texts. Some programs (like Eclipse) will show the output to System.err in red text, to make it more obvious that it is error text.
Simple System.out + System.err Example:
Here is a simple example that uses System.out and System.err :
Exchanging System Streams
Even if the 3 System streams are static members of the java.lang.System class, and are pre-instantiated at JVM startup, you can change what streams to use for each of them. Just set a new InputStream for System.in or a new OutputStream for System.out or System.err , and all further data will be read / written to the new stream.
To set a new System stream, use one of th emethods System.setIn() , System.setOut() or System.setErr() . Here is a simple example:
OutputStream output = new FileOutputStream("c:\\data\\system.out.txt"); PrintStream printOut = new PrintStream(output); System.setOut(printOut);
Now all data written to System.out should be redirected into the file «c:\\data\\system.out.txt». Keep in mind though, that you should make sure to flush System.out and close the file before the JVM shuts down, to be sure that all data written to System.out is actually flushed to the file.
Exit codes in Java – System.exit() method
This post will discuss the System exit codes in Java.
The System.exit(int) is the conventional and convenient means to terminate the currently running Java virtual machine by initiating its shutdown sequence. The argument of the exit() method serves as a status code to denotes the termination status. The argument can be either zero or nonzero:
1. Zero
The zero status code should be used when the program execution went fine, i.e., the program is terminated successfully.
2. Non-Zero
A nonzero status code indicates abnormal termination. Java allows us to use different values for different kinds of errors. A nonzero status code can be further positive or negative:
Positive status codes are often used for user-defined codes to indicate a particular exception.
Negative status codes are system generated error codes. They are generated due to some unanticipated exception, system error, or forced termination of the program.
- There are no pre-defined constants in Java to indicate SUCCESS and FAILURE messages.
- We should always use the proper status codes if our application interact with some tools or the program is called within a script.
- System.exit() method internally calls exit() method of the Runtime class. Therefore, the call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n) .
That’s all about exit codes in Java.
Average rating 4.47 /5. Vote count: 55
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Java System.in, System.out, and System.error
Java has 3 streams called System.in, System.out, and System.err which are commonly used to provide input to, and output from Java applications. Most commonly used is probably System.out for writing output to the console from console programs (command line applications).
System.in, System.out and System.err are initialized by the Java runtime when a Java VM starts up, so you don’t have to instantiate any streams yourself (although you can exchange them at runtime). I will explain each of these streams in deeper detail later in this tutorial.
System.in
System.in is an InputStream which is typically connected to keyboard input of console programs. In other words, if you start a Java application from the command line, and you type something on the keyboard while the CLI console (or terminal) has focus, the keyboard input can typically be read via System.in from inside that Java application. However, it is only keyboard input directed to that Java application (the console / terminnal that started the application) which can be read via System.in. Keyboard input for other applications cannot be read via System.in .
System.in is not used as often since data is commonly passed to a command line Java application via command line arguments, files, or possibly via network connections if the application is designed for that. In applications with GUI the input to the application is given via the GUI. This is a separate input mechanism from System.in.
System.out
System.out is a PrintStream to which you can write characters. System.out normally outputs the data you write to it to the CLI console / terminal. System.out is often used from console-only programs like command line tools as a way to display the result of their execution to the user. This is also often used to print debug statements of from a program (though it may arguably not be the best way to get debug info out of a program).
System.err
System.err is a PrintStream . System.err works like System.out except it is normally only used to output error texts. Some programs (like Eclipse) will show the output to System.err in red text, to make it more obvious that it is error text.
Simple System.out + System.err Example:
Here is a simple example that uses System.out and System.err :
Exchanging System Streams
Even if the 3 System streams are static members of the java.lang.System class, and are pre-instantiated at JVM startup, you can change what streams to use for each of them. Just set a new InputStream for System.in or a new OutputStream for System.out or System.err , and all further data will be read / written to the new stream.
To set a new System stream, use one of th emethods System.setIn() , System.setOut() or System.setErr() . Here is a simple example:
OutputStream output = new FileOutputStream("c:\\data\\system.out.txt"); PrintStream printOut = new PrintStream(output); System.setOut(printOut);
Now all data written to System.out should be redirected into the file «c:\\data\\system.out.txt». Keep in mind though, that you should make sure to flush System.out and close the file before the JVM shuts down, to be sure that all data written to System.out is actually flushed to the file.
System.exit(). Какой код выхода использовать?
Что является причиной того, что java программа прекращает любую свою активность и завершает свое выполнение? Основных причин может быть 2 (JLS Секция 12.8):
- Все потоки, которые не являются демонами, выполнены;
- Какой то из потоков вызывает метод exit() класса Runtime или же класса System и
SecurityManager дает добро на выполнение exit().
Именно значение 0 и возвращает JVM в первом, вышеописанном случае при своем завершении.
Как это можно проверить?
Тут нам на помощь приходит параметр командной строки ERRORLEVEL, который позволяет получить код выхода программы, которую мы запускали последней.
Как видим со скриншота код выхода равен 0.
Переходим ко второму случаю, с использованием метода exit().
Какие значения можно передавать в метод exit? Исходя из документации:
The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
Ага, варианта два: либо 0, либо любое ненулевое значение. Второй вариант можем разбить еще на два под варианта: любое отрицательное число и любое положительное число типа int.
Как видим, родительский процесс снова получил информацию об успешном завершении JVM.
А что же с nonzero значениями? Что, когда и в каком случае передавать?
Тут все просто — никаких требований для nonzero значений нету и следует руководствоваться лишь одним общим правилом:
- Возвращаем код выхода со значением >0 в случае, если мы ожидали что что то может случится нехорошее и оно таки случилось, например: некорректные данные в args[], или не удалось найти какой то важный для работы приложения файл, или не удалось подключиться к серверу и тд.
- Возвращаем код выхода со значением
И последний вариант: если нам известно, что код выхода дополнительно обрабатывается и дабы не выдумывать значения самому можно позаимствовать значения, которые используются на уровни ОС.
Например, для ОС семейства Windows существует целый список из 15999 кодов: System Error Codes, для семейства Linux свой список: sysexits.h
Java system error code
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter