Как завершить программу в java
Перейти к содержимому

Как завершить программу в java

  • автор:

System.exit() в Java – что это?

Java – язык программирования, имеющий множество приложений. При программировании для одного из этих приложений вы можете застрять на каком-то этапе этой программы. Что делать в этой ситуации? Есть ли способ выйти в этой самой точке? Если эти вопросы вас беспокоят, вы попали в нужное место.

Что вы можете сделать, это просто использовать метод System.exit(), который завершает текущую виртуальную машину Java, работающую в системе.

Как вы выходите из функции в Java?

Вы можете выйти из функции, используя метод java.lang.System.exit(). Этот метод завершает текущую запущенную виртуальную машину Java (JVM). Он принимает аргумент «код состояния», где ненулевой код состояния указывает на ненормальное завершение.

Если вы работаете с циклами Java или операторами switch, вы можете использовать операторы break, которые используются для прерывания / выхода только из цикла, а не всей программы.

Что такое метод System.exit()?

Метод System.exit() вызывает метод exit в классе Runtime. Это выходит из текущей программы, завершая виртуальную машину Java. Как определяет имя метода, метод exit() никогда ничего не возвращает.

Вызов System.exit (n) фактически эквивалентен вызову:

Функция System.exit имеет код состояния, который сообщает о завершении, например:

  • выход (0): указывает на успешное завершение.
  • выход (1) или выход (-1) или любое ненулевое значение – указывает на неудачное завершение.

Исключение: выдает исключение SecurityException.

Примеры

Выход: arr [0] = 1 arr [1] = 2 arr [2] = 3 Выход из цикла

Объяснение: В приведенной выше программе выполнение останавливается или выходит из цикла, как только он сталкивается с методом System.exit(). Он даже не печатает второй оператор печати, который говорит «Конец программы». Он просто завершает программу сам.

Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла

Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.

Как завершить программу в java

The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.

Following is the declaration for java.lang.System.exit() method:

exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination.

Class System

For simple stand-alone Java applications, a typical way to write a line of output data is:

See the println methods in class PrintStream .

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out , has been redirected to a file or other destination that is typically not continuously monitored. The encoding used in the conversion from characters to bytes is equivalent to Console.charset() if the Console exists, Charset.defaultCharset() otherwise.

Method Details

setIn

setOut

setErr

console

inheritedChannel

In addition to the network-oriented channels described in inheritedChannel , this method may return other kinds of channels in the future.

setSecurityManager

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

getSecurityManager

currentTimeMillis

See the description of the class Date for a discussion of slight discrepancies that may arise between «computer time» and coordinated universal time (UTC).

nanoTime

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) — no guarantees are made except that the resolution is at least as good as that of currentTimeMillis() .

Differences in successive calls that span greater than approximately 292 years (2 63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

For example, to measure how long some code takes to execute:

To compare elapsed time against a timeout, use instead of because of the possibility of numerical overflow.

arraycopy

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null , then a NullPointerException is thrown.

If src is null , then a NullPointerException is thrown and the destination array is not modified.

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length , the length of the source array.
  • destPos+length is greater than dest.length , the length of the destination array.

Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+ k ] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+ k -1 will already have been copied to destination array positions destPos through destPos+ k -1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

identityHashCode

getProperties

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties includes a value for each of the following keys unless the description of the associated value indicates that the value is optional.

Shows property keys and associated values

Key Description of Associated Value
java.version Java Runtime Environment version, which may be interpreted as a Runtime.Version
java.version.date Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD format, which may be interpreted as a LocalDate
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.vendor.version Java vendor version (optional)
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version, whose value is the feature element of the runtime version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version which may be interpreted as a Runtime.Version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version, whose value is the feature element of the runtime version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path (refer to ClassLoader.getSystemClassLoader() for details)
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator («/» on UNIX)
path.separator Path separator («:» on UNIX)
line.separator Line separator («\n» on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory
native.encoding Character encoding name derived from the host environment and/or the user’s settings. Setting this system property has no effect.

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

lineSeparator

On UNIX systems, it returns «\n» ; on Microsoft Windows systems it returns «\r\n» .

setProperties

The argument becomes the current set of system properties for use by the getProperty(String) method. If the argument is null , then the current set of system properties is forgotten.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

setProperty

clearProperty

getenv

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.»+name) permission. This may result in a SecurityException being thrown. If no exception is thrown the value of the variable name is returned.

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH ).

On UNIX systems the alphabetic case of name is typically significant, while on Microsoft Windows systems it is typically not. For example, the expression System.getenv(«FOO»).equals(System.getenv(«foo»)) is likely to be true on Microsoft Windows.

getenv

If the system does not support environment variables, an empty map is returned.

The returned map will never contain null keys or values. Attempting to query the presence of a null key or value will throw a NullPointerException . Attempting to query the presence of a key or value which is not of type String will throw a ClassCastException .

The returned map and its collection views may not obey the general contract of the Object.equals(java.lang.Object) and Object.hashCode() methods.

The returned map is typically case-sensitive on all platforms.

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.*») permission. This may result in a SecurityException being thrown.

When passing information to a Java subprocess, system properties are generally preferred over environment variables.

Terminating a Java Program

I found out ways to terminate (shut-down or stop) my Java programs. I found two solutions for it.

using return;
When I want to quit or terminate my program execution , I add this.

using System.exit() ;
Sometimes I used it. I read about System.exit() from this question.

So, I know a little on both them. But I am still confused as to how they actually work. Please check below codes.

I am sure that 2 will not appear. I would like to know is why return; or other codes can write below the statement of System.exit(0); and what was real definition for return; (because it is strange thing for me return without any variables or values) ?

Cataclysm's user avatar

7 Answers 7

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program — and the result will always be the same — JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do — and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you’d need to return void . If the method is declared to return a particular type, then you must specify the value to return — and this value must be of the specified type.

return would cause the program to exit only if it’s inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *