-4

What I am trying to do is initialize Boolean array and size of the array is long value.

public static  List<Integer> primesUpTo(long target) {

         boolean[] nonPrime = new boolean[target];

}

I am getting following Error:

possible loss of precision
         boolean[] nonPrime = new boolean[target];
                                          ^
  required: int
  found:    long

Can someone explain me please why I am unable to initialize Boolean array using long value and also I am unable to increment long value say for : boolean[] nonPrime = new boolean[target+1] also not working.Thanks for advance.

Abu Sufian
  • 991
  • 1
  • 6
  • 15
  • read the error - arrays can only be declared using an int value. If you can guarantee that `target` will fit into a `int` then cast it. Otherwise you are probably going to run out of memory. – Scary Wombat Nov 08 '16 at 07:03
  • Arrays are always initialized with an `int`. You can not make an array larger than `Integer.MAX_VALUE`. – marstran Nov 08 '16 at 07:04

1 Answers1

1

This is a language limitation.

Java has been criticized for not supporting arrays of more than 2^31−1 (about 2.1 billion) elements.[17][18][19] This is a limitation of the language; the Java Language Specification, Section 10.4, states that:

Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.[20]

https://en.m.wikipedia.org/wiki/Criticism_of_Java#Large_arrays

Answer found here: Do Java arrays have a maximum size?.

Community
  • 1
  • 1
mm759
  • 1,404
  • 1
  • 9
  • 7
  • Thanks for sharing information. I appreciate your approach to give information. I wonder people giving negative marking rather try to answer question. – Abu Sufian Nov 08 '16 at 10:31