• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Exception Question.

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its a very clear explanation.

Thanks.
reply
    Bookmark Topic Watch Topic
  • New Topic