aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception Question." Watch "Exception Question." New topic
Author

Exception Question.

Amisha Shah
Ranch Hand

Joined: Mar 03, 2006
Posts: 33
Question:

The following class will print '2' when compiled and run.

class Test
{
public static int[ ] getArray() { return null; }
public static void main(String[] args)
{
int index = 1;
try
{
getArray()[index=2]++;
}
catch (Exception e){ } //empty catch
System.out.println("index = " + index);
}
}
A. true
B. flase

output of this code is 2. i thought output is 1. can anyone eplain me how program work?


Amisha Shah.<br />SCJP 1.4
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809




at line 1, the value of 2 is assigned to index.
So basically line 1 will be like this....
getArray()[2]++;
getArray method returns null. Since u r retrieving third element of int array which is null. U will get get NullPointer exception, if u print it in catch by printStackTrace() mthod.
But since ur catch is empty, it does nothing and after catch normal execution follows.... and u will get the of value of index 2.

regards

Naseem.K


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
class Test
{
public static int[ ] getArray() { return null; }
public static void main(String[] args)
{
int index = 1;
try
{
getArray()[index=2]++;
}
catch (Exception e){ } //empty catch
System.out.println("index = " + index);
}
}
Steps:
1. getArray() called and return a reference X
2. index =2 executed and index is 2 now.
3. It runs X[2]++, an exception is thrown because X is null
4. catach clause do nothing
5. print out index
Uma Vinodh
Greenhorn

Joined: Apr 26, 2006
Posts: 28
Its a very clear explanation.

Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception Question.