Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method is used to terminate the execution of Java program in between?

Tags:

java

We used functions like exit() in C++ to abnormally terminate the execution of program, which function can we use in Java. For ex :- In following program I want to terminate the execution as soon the value of i is printed for 1st time.

//following is the program :  
class Lcm {
        public static void main( String args[] ) {

            int a = Integer.parseInt( args[0] );
            int b = Integer.parseInt( args[1] );

            for ( int i=1 ; i<=a*b ; i++ ) {
                if ( i%a==0 && i%b==0 ) {
                    System.out.println( "lcm is: " + i );
                    /* i want to terminate the program
                     * when the value of i is printed
                     * for very 1st time
                     */
                }
            }
        }
    }
}
like image 216
Anit Singh Avatar asked Sep 29 '11 17:09

Anit Singh


1 Answers

Use break to get out of the loop and let the function end naturally, or a plain return to exit the function altogether.

Perhaps it is finally time to learn to control your flow without goto statements and their equivalents (exit, longjmp, try..catch used for flow control etc).

like image 175
Blindy Avatar answered Nov 15 '22 15:11

Blindy