Forum Stats

  • 3,872,222 Users
  • 2,266,407 Discussions
  • 7,911,107 Comments

Discussions

About arrays of negative length

User_EKLLU
User_EKLLU Member Posts: 1 Green Ribbon

I created an array with a negative length using the Unsafe. Is that a bug?

Answers

  • Ana Kalemi
    Ana Kalemi Member Posts: 8 Green Ribbon

    You cannot use a negative integer as size, the size of an array represents the number of elements in it. Negative number of elements in an array makes no sense.

    Still if you do so, the program gets compiled without issues but, while executing it generates a runtime exception of type NegativeArraySizeException.

    On executing, this program generates a run time exception as shown below.

    Exception in thread "main" java.lang.NegativeArraySizeException
    at myPackage.Test.main(Test.java:5)
    

    My understanding of the sun.* classes including sun.misc.Unsafe is that they are specifically undocumented/unsupported. You are not supposed to be using them, as there is no published API that they agree to stick to, or semantics that they guarantee will hold.