Thursday, January 17, 2019

Java Programming Questions and Answers

1. 
What will be the output of the program?
public class Foo 
{  
    public static void main(String[] args) 
    {
        try 
        { 
            return; 
        } 
        finally 
        {
            System.out.println( "Finally" ); 
        } 
    } 
}
A.Finally
B.Compilation fails.
C.The code runs with no output.
D.An exception is thrown at runtime.
Answer: Option A
Explanation:
If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:
  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.

Java Programming :: Exceptions

Exercise :: Exceptions - Finding the output

1. 
What will be the output of the program?
public class Foo 
{  
    public static void main(String[] args) 
    {
        try 
        { 
            return; 
        } 
        finally 
        {
            System.out.println( "Finally" ); 
        } 
    } 
}
A.Finally
B.Compilation fails.
C.The code runs with no output.
D.An exception is thrown at runtime.
Answer: Option A
Explanation:
If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:
  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.

2. 
What will be the output of the program?
try 
{ 
    int x = 0; 
    int y = 5 / x; 
} 
catch (Exception e) 
{
    System.out.println("Exception"); 
} 
catch (ArithmeticException ae) 
{
    System.out.println(" Arithmetic Exception"); 
} 
System.out.println("finished");
A.finished
B.Exception
C.Compilation fails.
D.Arithmetic Exception
Answer: Option C
Explanation:
Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class.
If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

No comments:

Post a Comment

Which Python course is best for beginners?

Level Up Your Python Prowess: Newbie Ninjas: Don't fret, little grasshoppers! Courses like "Learn Python 3" on Codecade...