• 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

PL HELP - URGENT

 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Question ID :958005937570
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]++; // Line 1
}
catch (Exception e){ } //empty catch
System.out.println("index = " + index);
}
}
Ans: True
PROBLEM: why is the index 2 and not 3 . I understand that this is a postfix operator ++ but still at the end the value fo index shd be 3 i think.
Morever, i have not come accross any method call
which has an array dimension like line 1
Thanks in advance
padmini
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The ++ operator is not applied to 'index' but the result of getArray(). However that is null, so a nullPointer- or possibly a indexOutOfRangeException will be thrown, and caught by the catch-statement resulting in the printing of index (that previously had been assigned 2).
if you change the code to

You should get 3. See the difference?
/Mike
[This message has been edited by Mikael Jonasson (edited July 05, 2001).]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic