in JAVA by
What is the output of the following Java program?

public class Calculation   

{  

    int a;   

    public Calculation(int a)  

    {  

        this.a = a;  

    }  

    public int add()  

    {  

        a = a+10;   

        try   

        {  

            a = a+10;   

            try   

            {  

                a = a*10;   

                throw new Exception();   

            }catch(Exception e){  

                a = a - 10;  

            }  

        }catch(Exception e)  

        {  

            a = a - 10;   

        }  

        return a;  

    }  

      

    public static void main (String args[])  

    {  

        Calculation c = new Calculation(10);  

        int result = c.add();  

        System.out.println("result = "+result);  

    }  

}

1 Answer

0 votes
by

Output of the above program is :

Output

result = 290

Explanation

The instance variable a of class Calculation is initialized to 10 using the class constructor which is called while instantiating the class. The add method is called which returns an integer value result. In add() method, a is incremented by 10 to be 20. Then, in the first try block, 10 is again incremented by 10 to be 30. In the second try block, a is multiplied by 10 to be 300. The second try block throws the exception which is caught by the catch block associated with this try block. The catch block again alters the value of a by decrementing it by 10 to make it 290. Thus the add() method returns 290 which is assigned to result. However, the catch block associated with the outermost try block will never be executed since there is no exception which can be handled by this catch block.

Java: String Handling Interview Questions

There is given a list of string handling interview questions with short and pointed answers. If you know any string handling interview question, kindly post it in the comment section.

Related questions

0 votes
asked May 4, 2021 in JAVA by SakshiSharma
0 votes
asked Oct 24, 2020 in JAVA by sharadyadav1986
0 votes
asked Apr 8, 2021 in JAVA by SakshiSharma
...