Performance Testing – Multiple Choice Questions and Answers – MCQ1

HOME

























Java – Multiple Choice Questions and Answers – Arrays

HOME




class array_output 
    {
        public static void main(String args[]) 
        {
            int array_variable [] = new int[10];
	        for (int i = 0; i < 10; ++i) 
            {
                array_variable[i] = i;
                System.out.print(array_variable[i] + " ");
                i++;
            }
        } 
   }


public class array_output {

    public static void main(String args[])
    {
        char array_variable [] = new char[10];
        for (int i = 0; i < 10; ++i)
        {
            array_variable[i] = 'i';
            System.out.print(array_variable[i] + "");
        }
    }
}

public class array_output {
    public static void main(String args[])
    {
        double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
        double result;
        result = 0;
        for (int i = 0; i < 6; ++i)
            result = result + num[i];
            System.out.print(result/6);

    }
}




public class Test {
    public static void main(String[] args) {
        String[] arr = {"Java", "Python", "C++"};
       System.out.println(arr[1]);
    }
}



public class Test {
    public static void main(String[] args) {
       int[] arr = new int[5];
      System.out.println(arr[1]);
    }
}

public class array_output {
    public static void main(String args[])
    {
        int[] arr = {1, 2, 3, 4};
        System.out.println(arr.length);
    }
}





public class array_output {
    public static void main(String args[])
    {
        int[] arr = {2, 4, 6, 8};
        System.out.println(arr[arr.length]);
    }
}

public class array_output {
    public static void main(String args[]) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 2;
        }
        System.out.println(arr[2]);
    }
}

public class array_output {
    
    public static void main(String args[]) {
        int[] arr = {10, 20, 30, 40};
        System.out.println(arr[1] + arr[2]);
    }
}



Java – Multiple Choice Questions and Answers – Strings

HOME




class Test
    {
        public static void main(String args[]) 
        {
            int array_variable [] = new int[10];
	        for (int i = 0; i < 10; ++i) 
            {
                array_variable[i] = i;
                System.out.print(array_variable[i] + " ");
                i++;
            }
        } 
   }


public class Test {
    
    public static void main(String args[]) {
        String obj = "I" + "like" + "Java";
        System.out.println(obj);
    }
}

public class Test {
    
    public static void main(String args[]) {
        String obj = "I LIKE JAVA";
        System.out.println(obj.charAt(3));
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "I LIKE JAVA";
        System.out.println(obj.length());
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "hello";
        String obj1 = "world";
        String obj2 = obj;
        obj2 = " world";
        System.out.println(obj + " " + obj2);
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "hello";
        String obj1 = "world";
        String obj2 = "hello";
        System.out.println(obj.equals(obj1) + " " + obj.equals(obj2));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("Hello World".indexOf('W'));
    }
}



public class Test {

    public static void main(String args[]) {
        System.out.println("Java".compareTo("Java"));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("abc".substring(1, 3));
    }
}





public class Test {

    public static void main(String args[]) {
        System.out.println("abc".repeat(3));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("Hello".replace('e', 'a'));
    }
}

public class Test {

    public static void main(String args[]) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");
        System.out.println(s1 == s2);
    }
}



Java – Multiple Choice Questions and Answers – Inheritance & Polymorphism

HOME



 class Apple {
       public void print() { System.out.println("Apple"); }
   }
   class Banana extends Apple {
       public void print() { System.out.println("Banana"); }
   }
   public class Test {
       public static void main(String[] args) {
           Apple  apple = new Banana();
           apple.print();
       }
   }



 class Apple {
       public void print() { System.out.println("Apple"); }
   }
   class Banana extends Apple {
       public void print() { System.out.println("Banana"); }
   }
   public class Test {
       public static void main(String[] args) {
           Apple  apple = new Apple();
           apple.print();
       }
   }

class A {
    A(int x) { }
}

class B extends A {
    B(int x) {
        System.out.println("Constructor B");
    }
}

public class Test {
    public static void main(String[] args) {
        B obj = new B(10);
    }
}

class Parent {
    void method() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
}

public class Test {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.method();
    }
}






  class Parent {
    public void print() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    public void print() {
        System.out.println("Child");
        super.print();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.print();
    }
}

package pack1;
public class A {
    public void display() {
        System.out.println("Hello from A");
    }
}

package pack2;
import pack1.A;
public class B {
    public static void main(String args[]) {
        A obj = new A();
        obj.display();
    }
}


class A 
    {
        int i;
        void display() 
        {
            System.out.println(i);
        }
    }    

    class B extends A 
    {
        int j;
        void display() 
        {
            System.out.println(j);
        }
    }    
    
   class Test
    {
        public static void main(String args[])
        {
            B obj = new B();
            obj.i=1;
            obj.j=2;   
            obj.display();     
        }
   }

 class A 
    {
        int i;
    }    

    class B extends A 
    {
        int j;
        void display() 
        {
            super.i = j + 1;
            System.out.println(j + " " + i);
        }
    }    

    class Test 
    {
        public static void main(String args[])
        {
            B obj = new B();
            obj.i=1;
            obj.j=2;   
            obj.display();     
        }
   }





public class Parent {
    void m1(String x) {
        System.out.println("One");
    }
}

public class Derived extends Parent{
    public void m1(String x) {
        System.out.println("Two");
        super.m1(null);
    }
}

public class Test {
    public static void main(String[] args){
        Parent obj = new Derived();
        obj.m1(null);
    }
}

public class Test{

    void m1(String x){
        System.out.println("One");
    }
    
    protected void m1(String x, String y){
        System.out.println("Two");
    }
    
    public static void main(String[] args){
        Test obj = new Test();
        obj.m1("ABC");
        obj.m1("PQR", "XYZ");
    }
}

public class PolymorphismDemoClass {
    void add(int x, int y){
        System.out.println("1. Addition is: " +(x+y));
    }
    
   void add(int y, int x){
        System.out.println("2. Addition is: " +(x+y));
    }
    
   public static void main(String[] args){
        PolymorphismDemoClass obj = new PolymorphismDemoClass();
        obj.add(20, 30);
    }
}


Java – Multiple Choice Questions and Answers – Exception Handling

HOME



public class QAAutomation {
    
     public static void main(String[] args) {
        try {
            System.out.println("Inside try");
            throw new RuntimeException("Error");
        } finally {
            System.out.println("Inside finally");
        }
    }
}

 public class QAAutomation {
    
    static void method() throws Exception {
        throw new Exception("Error occurred");
    }

    public static void main(String[] args) {
        method();
    }
}


 class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new CustomException("Custom error occurred");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

public class Test {
    
    public static void main(String args[]) {
        try {
            int a, b;
            b = 0;
            a = 5 / b;
            System.out.print("A");
        } catch (ArithmeticException e) {
            System.out.print("B");
        } finally {
            System.out.print("C");
        }
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            int i, sum;
            sum = 10;
            for (i = -1; i < 3 ;++i)
                sum = (sum / i);
        }
        catch(ArithmeticException e)
        {
            System.out.print("0");
        }
        System.out.print(sum);
    }
}



public class Test{
    public static void main(String[] args) {
        try {
            System.exit(0);
        } finally {
            System.out.println("Finally executed");
        }
    }
}



  public class Test {
         public static void main(String[] args) {
             String str = null;
             try {
                 System.out.println(str.length());
             } catch (NullPointerException e) {
                 System.out.println("Caught a NullPointerException");
             }
         }
     }

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Test {
    public static void readFile() throws IOException {
        File file = new File("example.txt");
        FileReader reader = new FileReader(file);
        reader.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("IOException handled");
        }
    }
}


public class Test {
    
    public static void main(String[] args) {

        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
            int division = 10 / 0;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Finally block executed");
        }
        System.out.println("Rest of the program");
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            System.out.print("Hello" + " " + 1 / 0);
        }
        catch(ArithmeticException e)
        {
            System.out.print("World");
        }
    }
}




public class Test {

    public static void main(String[] args) {
        try {
            throw new Exception("First Exception");
        } catch (Exception e) {
            try {
                throw new Exception("Second Exception");
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new Error("Fatal error");
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Error e) {
            System.out.println("Error");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            int[] array = new int[5];
            System.out.println(array[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException");
        } finally {
            System.out.println("Finally block executed.");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();
        } catch (RuntimeException e) {
            System.out.println("RuntimeException");
        } catch (Exception e) {
            System.out.println("Exception");
        }
    }
}


JAVA – Multiple Choice Questions and Answers

HOME

Java – Multiple Choice Questions and Answers – Method, Overloading, Overriding

HOME



class box 
    {
        int width;
        int height;
        int length;
        int volume;
        void volume(int height, int length, int width) 
        {
             volume = width*height*length;
        } 
    }    
    class Prameterized_method
    {
        public static void main(String args[])
        {
            box obj = new box();
            obj.height = 1;
            obj.length = 5;
            obj.width = 5;
            obj.volume(3,2,1);
            System.out.println(obj.volume);        
        } 
     }

 class equality 
    {
        int x;
        int y;
        boolean isequal()
        {
            return(x == y);  
        } 
    }    
    class Output 
    {
        public static void main(String args[])
        {
            equality obj = new equality();
            obj.x = 5;
            obj.y = 5;
            System.out.println(obj.isequal());
        } 
    }


 class overload 
    {
        int x;
 	int y;
        void add(int a) 
        {
            x =  a + 1;
        }
        void add(int a, int b)
        {
            x =  a + 2;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 0;
            obj.add(6);
            System.out.println(obj.x);     
        }
   }

class overload 
    {
        int x;
 	    int y;
        
       void add(int a)
        {
            x =  a + 1;
        }
        void add(int a , int b)
        {
            x =  a + 2;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 0;
            obj.add(6, 7);
            System.out.println(obj.x);     
        }
    }

class overload 
   {
        int x;
 	    double y;
        void add(int a , int b) 
        {
            x = a + b;
        }
        void add(double c , double d)
        {
            y = c + d;
        }
        overload() 
        {
            this.x = 0;
            this.y = 0;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 2;
            double b = 3.2;
            obj.add(a, a);
            obj.add(b, b);
            System.out.println(obj.x + " " + obj.y);     
        }
   }



class area 
    {
        int width;
        int length;
        int volume;
        area() 
        {
           width=5;
           length=6;
        }
        void volume() 
        {
             volume = width*length*height;
        } 
    }    
    class cons_method 
    {
        public static void main(String args[])
        {
            area obj = new area();
            obj.volume();
            System.out.println(obj.volume);        
        } 
    }



 class test 
    {
        int a;
        int b;
        test(int i, int j) 
        {
            a = i;
            b = j;
        }
        void meth(test o) 
        {
            o.a *= 2;
            o.b /= 2;
        }          
    }    
    class Output 
    {
        public static void main(String args[])
        {
            test obj = new test(10 , 20);
            obj.meth(obj);
            System.out.println(obj.a + " " + obj.b);        
        } 
    }

class Output {
    public static int sum(int... x) {
        int total = 0; 
        for (int num : x) { 
            total += num;
        }
        return total;
    }

    public static void main(String args[]) {
        System.out.println(sum(10));             
        System.out.println(sum(10, 20));         
        System.out.println(sum(10, 20, 30));     
        System.out.println(sum(10, 20, 30, 40)); 
    }
}

a) only sum(10)
b) only sum(10,20)
c) only sum(10) & sum(10,20)
d) all of the mentioned


class Test
{
 public void m1 (int i,float f)
 {
  System.out.println(" int float method");
 }
 
 public void m1(float f,int i)
  {
  System.out.println("float int method");
  }
 
  public static void main(String[]args)
  {
    Test test =new Test();
       test.m1(20,20);
   }
}

class Test {
    void show(int a) {
        System.out.println("int method: " + a);
    }

    void show(double a) {
        System.out.println("double method: " + a);
    }

    public static void main(String[] args) {
        Test obj = new Test();
        obj.show(10);      // Line 1
        obj.show(10.5);    // Line 2
        obj.show('A');     // Line 3
    }
}




class Derived  
{ 
    public void getDetails() 
    { 
        System.out.printf("Derived class "); 
    } 
} 
  
public class Test extends Derived 
{ 
    public void getDetails() 
    { 
        System.out.printf("Test class "); 
        super.getDetails(); 
    } 
    public static void main(String[] args) 
    { 
        Derived obj = new Test(); 
        obj.getDetails(); 
    } 
}

import java.io.IOException;

class Derived {
    public void getDetails() throws IOException { // Line 4
        System.out.println("Derived class");
    }
}

public class Test extends Derived {
    public void getDetails() throws Exception { // Line 10
        System.out.println("Test class");
    }

    public static void main(String[] args) throws IOException { // Line 14
        Derived obj = new Test();
        obj.getDetails();
    }
}

class Derived 
{
    protected final void getDetails()
    {
        System.out.println("Derived class");
    }
}

public class Test extends Derived
{
    protected final void getDetails()
    {
        System.out.println("Test class");
    }
    public static void main(String[] args)
    {
        Derived obj = new Derived();
        obj.getDetails();
    }
}

public class Test
{
    public int getData(String temp) throws IOException
    {
        return 0;
    }
    public int getData(String temp) throws Exception
    {
        return 1;
    }
    public static void main(String[] args)
    {
        Test obj = new Test();
        System.out.println(obj.getData("Happy"));    
    }
}


Java – Multiple Choice Questions and Answers – Basic Java

HOME



class increment {
        public static void main(String args[]) 
        {        
             int g = 3;
             System.out.print(++g * 8);
        } 
    }

class variable_scope 
    {
        public static void main(String args[]) 
        {
            int x;
            x = 5;
            {
	        int y = 6;
	        System.out.print(x + " " + y);
            }
            System.out.println(x + " " + y);
        } 
    }


public class Test {
    public static void main(String[] args) {
        int x = 5;
        System.out.println(x++);
    }
}

public class Test {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = new String("Java");
        System.out.println(s1 == s2);
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(10 + 20 + "30");
    }
}



public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println(a > b ? a : b);
    }
}



public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        System.out.println(a + b * 2);
    }
}

int x = 10;
int y = 3;
System.out.println(x / y);

int a = 5;
System.out.println(a++); 
System.out.println(a);

int x = 4;
System.out.println((x > 3) || (x < 2));



public class Test {
    public static void main(String[] args) {
        int x = 5;
        if (x < 5)
            System.out.println("Less");
        else if (x == 5)
            System.out.println("Equal");
        else
            System.out.println("More");
    }
}

public class Test {
    public static void main(String[] args) {
        int num = 2;
        switch(num + 1) {
            case 1: System.out.println("One");
            case 2: System.out.println("Two");
            case 3: System.out.println("Three");
            default: System.out.println("Default");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 3) {
            System.out.print(i + " ");
            i++;
        }
    }
}

public class Test {
    public static void main(String[] args) {
        int x = 4;
        if (x % 2 == 0)
            if (x % 3 == 0)
                System.out.println("Divisible by 6");
            else
                System.out.println("Divisible by 2 but not by 3");
    }
}


Multiple questions on Exception Handling in Java

HOME

In this tutorial, you will see the various questions related to Exception Handling.

Example1

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, we have multiple catch blocks with different types of exceptions. 30 is divided by 0 which throws ArithmeticException. So, the catch block for ArithmeticException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example2

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 30 / 15;
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, we are trying to access a[5] where index 5 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example3

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];

			System.out.println(a[7]);
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Output
ArrayIndexOutOfBounds Exception occurs
Continue the program..

Here, we are trying to access a[7] where index 7 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example4

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
			System.out.println(a[10]);
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, the try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed. So, the first exception is 30 divided by 0 which throws an ArithmeticException. So, the catch block for ArithmeticException is executed. Once the corresponding catch block is executed, the program runs in normal flow.


Example5

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            String name = null;
            System.out.println(name.length());
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
        } catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("Continue the program..");
    }
}

Here, the try block contains NullPointerException. But, there is no NullPointerException present in any of the catch blocks. In such a case, the catch block containing the parent exception class Exception will be invoked.


Example6

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (Exception e) {
			System.out.println("common task completed");
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, the order of exceptions is not maintained like most specific to general exceptions. The exception is the parent exception, so should be mentioned as the last exception. As a result, there is a compile-time error.


Example7

public class ExceptionHandlingDemo {

    public static void main(String args[]) {
        int x = 0;
        int y = 10;
        int z = y/x;
    }
}

Here, ArithmeticException is an unchecked exception that is not checked at a compiled time. So the program compiles fine but throws ArithmeticException.


Example8

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            int a[] = { 1, 2, 3, 4 };
            for (int i = 1; i <= 4; i++) {
                System.out.println("a[" + i + "]=" + a[i]);
            }
        }

        catch (Exception e) {
            System.out.println("error = " + e);
        }

        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occured");
        }
    }
}

Here, ArrayIndexOutOfBoundsException has been already caught by the base class Exception. When a subclass exception is mentioned after the base class exception, then an error occurs.


Example9

public class Example9 {

	public static void main(String[] args) {
		try {
			int a[] = { 1, 2, 3, 4 };
			for (int i = 1; i <= 4; i++) {
				System.out.println("a[" + i + "]=" + a[i]);
			}
		}

		catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occured");
		}

		catch (Exception e) {
			System.out.println("error = " + e);
		}
	}
}

Here, the try block prints a[1] to a[3] and then throws ArrayIndexOutOfBoundsException which is handled by the corresponding catch block.


Example10

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try and catch block 1
			try {
				System.out.println("going to divide by 0");
				int b = 40 / 0;
			}
			catch (ArithmeticException e) {
				System.out.println(e);
			}

			// inner try and catch block 2
			try {
				int a[] = new int[5];

				// assigning the value out of array bounds
				a[5] = 4;
			}
			catch (ArrayIndexOutOfBoundsException e) {
				System.out.println(e);
			}

			System.out.println("No more inner try catch block");
		}

		// catch block of outer try block
		catch (Exception e) {
			System.out.println("Handled the exception of outer try");
		}

		System.out.println("Continue the program..");
	}
}

Here, the first inner try-catch block is executed. Then second inner try-catch block is executed and at last outer try-catch block is executed. Post all these, the program runs in normal flow.


Example11

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

        // outer try block
        try {

            // inner try block 1
            try {

                // inner try block 2
                try {
                    int x = 25 / 0;
                    System.out.println("Value of x :" + x);
                }

                // to handles ArrayIndexOutOfBoundsException
                catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Arithmetic exception");
                    System.out.println(" inner try block 2");
                }
            }

            // to handle ArrayIndexOutOfBoundsException
            catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Arithmetic exception");
                System.out.println("inner try block 1");
            }
        }

        // to handle ArithmeticException
        catch (ArithmeticException e) {
            System.out.println(e);
            System.out.println("Outer try block");
        } catch (Exception e) {
            System.out.print("Exception");
            System.out.println("Handled in main try block");
        }
    }
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it also does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. 


Example12

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try block 1
			try {

				// inner try block 2
				try {
					int x = 25 / 0;
					System.out.println(x);
				}

				// to handles ArrayIndexOutOfBoundsException
				catch (ArrayIndexOutOfBoundsException e) {
					System.out.println("Arithmetic exception");
					System.out.println(" inner try block 2");
				}
			}

			// to handle ArithmeticException 
			catch (ArithmeticException e) {
				System.out.println("Arithmetic exception");
				System.out.println("inner try block 1");
			}
		}

		// to handle ArithmeticException
		catch (ArithmeticException e) {
			System.out.print(e);
			System.out.println("Outer try block");

		} catch (Exception e) {
			System.out.print("Exception");
			System.out.println("Handled in main try block");
		}
	}
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it does handle the exception, so the catch block of inner try block 1 handles the exception.


Example13

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			// below code do not throw any exception
			int data = 25 / 5;
			System.out.println(data);
		}

		// catch won't be executed
		catch (NullPointerException e) {
			System.out.println(e);
		}

		// This is executed whether exception occurs or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Output
5
finally block is always executed
Continue the Program ..

Here, no exception is thrown, so the catch block is not executed. finally block is always executed irrespective the catch block is executed or not.


Example14

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {

			System.out.println("Inside the try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		catch (NullPointerException e) {
			System.out.println("Exception handled");
			System.out.println(e);
		}

		// executes regardless of exception occurred or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception, however, the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally.


Example15

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		
       try {

			System.out.println("Inside try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		// handles the Arithmetic Exception 
		catch (ArithmeticException e) {
			System.out.println("Exception is handled");
			System.out.println(e);
		}

		// executes regardless of exception occured or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.


Example16

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a = 0;
			System.out.println("a = " + a);
			int b = 20 / a;
			System.out.println("b = " + b);
		}

		catch (ArithmeticException e) {
			System.out.println("Divide by zero error");
		}

		finally {
			System.out.println("inside the finally block");
		}
	}
}

Here, a is printed. Then, 20 is divided by 0, which throws ArithmeticException and control goes inside the catch block. Also, the finally block is always executed whether an exception occurs or not.


Example 17

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		int data = 50 / 0; // may throw exception

		System.out.println("rest of the code");
	}

}

Here, there is no try-catch block. So, the error is thrown.


Example 18

public class ExceptionHandlingDemo  {

	public static void main(String[] args) {
		try {
			int data1 = 50 / 0; 

		}
		catch (Exception e) {
			// generating the exception in catch block
			String name = null;
			System.out.println(name.length());
			
		}
		System.out.println("Continue the Program ..");
	}

}

Output
Exception in thread "main" java.lang.NullPointerException

Here, the catch block didn’t contain the exception code. So, enclose the exception code within a try block and use a catch block only to handle the exceptions.


Example 19

public class ExceptionHandlingDemo {

	static void checkEligibilty(int age, int marks) {
		if (age < 18 && marks < 90) {
			throw new ArithmeticException("Student is not eligible for admission");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String[] args) {
		System.out.println("Welcome to the Admission process!!");
		checkEligibilty(17, 80);
		System.out.println("Continue the Program ..");
	}
}

Here, an unchecked exception was thrown and it is not handled, so the program halts.


Example 20

public class ExceptionHandlingDemo {

	public static void myMethod(int testnum) throws Exception {
		System.out.println("start - myMethod");
		if (testnum < 100)
			throw new Exception();
		System.out.println("end - myMethod");
		return;
	}

	public static void main(String args[]) {
		int testnum = 90;
		try {
			System.out.println("try - first statement");
			myMethod(testnum);
			System.out.println("try - last statement");
		} catch (Exception ex) {
			System.out.println("An Exception");
		} finally {
			System.out.println("finally");
		}
		System.out.println("Out of try/catch/finally - statement");
	}
}

Here, an exception is thrown in the try block, which is handled by the catch block. A finally block is executed, and then the program continues as usual.


Example 21

public class ExceptionHandlingDemo {

   public static void main(String args[]) {
      try {
         throw 10;
      }
      catch(int e) {
         System.out.println("Got the  Exception " + e);
      }
  }
}

In Java, only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exceptions. So basic data types can not be thrown at all.


Example 22

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		
      try {
			throw new Test();
		} catch (Test t) {
			System.out.println("Got the Test Exception");
		} finally {
			System.out.println("Inside finally block ");
		}
	}
}

The output of the above program is


Example 23

class Base extends Exception {
}

class Derived extends Base {
}

 class ExceptionHandlingDemo  {

    public static void main(String[] args) {
        try {

            throw new Derived();
        } catch (Base b) {
            System.out.println("Caught base class exception");
        } catch (Derived d) {
            System.out.println("Caught derived class exception");
        }
    }
}


Example 24

public class ExceptionHandlingDemo {

	String str = "a";

    void A() {
        try {
            str += "b";
            B();
        } catch (Exception e) {
            str += "c";
        }
    }

    void B() throws Exception {
        try {
            str += "d";
            C();
        } catch (Exception e) {
            throw new Exception();
        } finally {
            str += "e";
        }

        str += "f";

    }

    void C() throws Exception {
        throw new Exception();
    }

    void display() {
        System.out.println(str);
    }

    public static void main(String[] args) {
        ExceptionHandlingDemo object = new ExceptionHandlingDemo();
        object.A();
        object.display();
    }

}

}

‘throw’ keyword is used to explicitly throw an exception.
Call to method C() throws an exception. Thus, control goes to the catch block of method B() which again throws an exception. Then finally block is always executed even when an exception occurs. Now, control goes to the catch block of method A().


Example 25

public class ExceptionHandlingDemo {

	 void m() {
        int data = 50 / 0;
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 26

public class ExceptionHandlingDemo {

	void m() {
        throw new IOException("device error");// checked exception
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, it is propagated to the p() method where the exception is supposed to be handled, but as it is checked Exception which can not be handled by Exception.


Example 27

public class ExceptionHandlingDemo {

    void m() {
        throw new ArithmeticException("Arithmetic Exception occured ");
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method – ArithmeticException where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 28

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			int i, sum;
			sum = 10;
			for (i = -1; i < 3; ++i)
				sum = (sum / i);
		} catch (ArithmeticException e) {
			System.out.print("0");
		}
		System.out.print(sum);
	}
}

Here, the value of the variable sum is printed outside of the try block, the sum is declared only in the try block, and outside try block it is undefined.


Example 29

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			String str = "beginnersbook";
			System.out.println(str.length());
			char c = str.charAt(0);
			c = str.charAt(40);
			System.out.println(c);
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("StringIndexOutOfBoundsException!!");
		}
	}
}

Here, an exception occurred because the referenced index was not present in the String.


Example 30

public class ExceptionHandlingDemo {

    public static void main(String[] args) {

            try {
                int num = Integer.parseInt("XYZ");
                System.out.println(num);
            } catch (StringIndexOutOfBoundsException e) {
                System.out.println("String IndexOutOfBounds Exception occurred!!");
            } catch (NumberFormatException e) {
                System.out.println("Number format exception occurred");
            } catch (Exception e) {
                System.out.println("Exception occurred");
            }
        }
    }

Here, an exception is not of type StringIndexOutOfBounds, so moved to the next catch where the exception is handled.