Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Question.

 
Amisha Shah
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




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
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its a very clear explanation.

Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic