How To Use End Program In Java?

455    Asked by ashish_1000 in Java , Asked on Sep 22, 2023

I discovered a few ways to exit the Java programs. There are two solutions that I have found. One is using the return statement. On wishing to end or quit the program execution, I use this. The second is utilizing the System. exit(). However, I am confused as to how these work exactly. Have a look at the codes below:

public class Testing {
public static void main(String... str) {
    System.out.println(1);
    System.exit(0);
    System.out.println(2);
    return;
 }
}

I am quite confident that 2 won’t appear. I want to know why returns and other codes are written below the statement of the System. exit (), and what is the actual definition of return?

Answered by Chris Dyer

 System. exit() is another way to the compiler. It does not read and understand that the entire program will be terminated at that moment. The OS or shell can read the integer, which is transferred back into the System. exit() method. It is a rule for 0 to imply that the program quit and everything is fine. It is the developer’s call to document the return values for the users. However, return refers to a constrained keyword that the compiler is aware of. Return returns a value and terminates the present function’s run going back up the stack to that function that triggered it. System. exit() ends the JVM> After this, nothing is executed at all. Return is usually deployed to terminate or exit a method. In case the return type is void, you may use return. However, it is not a good habit. There is no need to do anything to end program in Java, until the infinite loop flows.



Hence return does not actually terminate the java program but terminates the java function (void). The function is the prime function of your application here. Return will also exit the application, but in your case, the return is a waste as the function will exit directly after the return. The system. exit() is capable of entirely terminating your program, and it will also close any window that is open.



Your Answer

Interviews

Parent Categories