Wednesday 27 February 2013

30. What will be output if you try to compile and run the following code, but there

30. What will be output if you try to compile and run the following code, but there
is no file called Hello.txt in the current directory?



Choices:
a. No such file found
b. No such file found , -1
c. No such file found, Doing finally, -1
d. 0


Answer:-
C is correct. Firstly after construction of Test class, System.out.println(myMethod()) will be invoked. This will invoke myMe thod(). Since Hello.txt is not present in the current directory, FileNotFoundException will be thrown in the try block. It will be caught in the catch block, where first "No such file found" will be printed. Then return -1 will be executed. But please note that before control passes back to main method, finally block will be executed and thus "Doing finally" will be printed. Finally "-1" will be printed.

==

import java.io.*;

public class Test
{
        public static void main(String argv[])
  {
        Test t = new Test();
        System.out.println(t.myMethod());
  }

                public int myMethod()
  {
        try
  {
                FileInputStream dis = new FileInputStream("Hello.txt");
                }
  catch (FileNotFoundException fne)
  {
                  System.out.println("No such file found");
                        return -1;
                }
                               catch(IOException ioe)
  {
                }
  finally
  {
        System.out.println("Doing finally");
        }
        return 0;
        }
}

 

No comments:

Post a Comment