Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

-ve array subscript

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is this allowed?

int[][] a = new int[5][-1];

How come the compiler allows it but ends up in runtime exception - NegativeArraySizeException?

what exactly are the things the compiler checks in a declared array?
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by M Krishnan:
Is this allowed?

int[][] a = new int[5][-1];

How come the compiler allows it but ends up in runtime exception - NegativeArraySizeException?

what exactly are the things the compiler checks in a declared array?




Object creating is the matter of runtime. What compiler can check is for the
proper syntax allowed in Java as:

int [3] arr; //Compiler error, because virtual machine does not allocate
space until you actually instantiate the array object.

int[] arr = new int[]; //compiler error, missing dimension
int[] [] arr = new int[][3]; //compiler error too
int[] = new int[3]{12,3,4};//compiler error

So these are some cases where compiler can check us, but providing negative
array size or size beyond the array scope can only be determined at run
time. And there are exceptions to be thrown if any of such cases occur.


Thanks,
 
permaculture is largely about replacing oil with people. And one tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic