Page 344 - CITS - Computer Software Application -TT
P. 344

COMPUTER SOFTWARE APPLICATION - CITS




           public class SampleExitMethod {
             public static void exampleMethod(int[] array1) {
               for (int i = 0; i < array1.length; i++) {
                 //Check condition for i
                 if (i > 4) {
                   System.out.println(“Terminating JVM...”);
                //Terminates JVM when if condition is satisfied
                   System.exit(0);
                 }
                 System.out.println(“Array Index: “ + i + “ Array Element: “ + array1[i]);
               }
             }
             public static void main(String[] args) {
               int[] array1 = { 0, 2, 4, 6, 8, 10, 12, 14, 16 };
               //function call
               exampleMethod(array1);
             }
           }
           Output:
           Array Index: 0 Array Element: 0
           Array Index: 1 Array Element: 2
           Array Index: 2 Array Element: 4
           Array Index: 3 Array Element: 6
           Array Index: 4 Array Element: 8
           Terminating JVM...
           Explanation:
           In the above program, an array is being accessed till its index is 4. Until if condition is false i.e., array index <= 4,
           JVM will give Array index and element stored at that index as the output.
           Once the if condition is true i.e., array index > 4, JVM will execute statements inside the if condition. Here it will
           first execute the print statement and when exit(0) method is called it will terminate JVM and program execution.
           Example 2
           Let’s see one more example of exit() method in a try-catch-finally block.
           import java.io.BufferedReader;
           import java.io.FileReader;
           import java.io.IOException;
           public class check {
           public static void main(String[] args) {
           try {

                 //Reads “file.txt” file
                 BufferedReader br = new BufferedReader(new FileReader(“file.txt”));
           // Closes bufferreader br
                 System.out.println(br.readLine());
                 br.close();
              } // Catches exception
               catch (IOException e) {
                 System.out.println(“Exception caught. Terminating JVM.”);
                 System.exit(0);



                                                           331
                               CITS : IT&ITES - Computer Software Application - Lesson 85 - 93
   339   340   341   342   343   344   345   346   347   348   349