Share on Google+Share on Google+

SCJP Module-2 Question-3

The program given below is will help you understanding of exception handling of java and also helpful for SCJP examination.

What is the Output of below code after compilation :

1 .public class Question3{
2 .public static void main(String[] args) {
3 .try {
4 .int a= (int)(Math.random()*5);
5 .if(a<=2.5)
6 .System.out.println("a="+a);
7 .else
8 .throw new Exception("a>2.5");
9. } catch (Exception e){

10. System.err.println(e.getMessage() );
11. System.err.println("Value of a="+a);
12. } } }

Find the output of the following code :

1.An Exception is raised during compilation.

2.An Exception is thrown at run time.

3.Unresolved compilation problem.

4.a=2 or a=1 or i >2.5 Value of i =null

Answer :


Explanation :

This code will not compile because  variable "a" at line number 11 , is not recognize by compiler since "a" is a local variable declared inside "Try" block. This code can be corrected by applying code line "static String a  = null ;"at line number2(or immediately after declaration of class & before 'main( )').



Posted on: July 7, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null