0

I am getting "incompatible types: possibly loss of conversion from long to int" exception in this line: boolean arr[] = new boolean [limit]; I don't understand why this is happening since I am storing the input value in long, how is it getting converted to int?

 import java.util.*;
 import java.io.*;
 public class PrimeSieve
{
public static void main (String args [])
{
   //getting the number
   Scanner x = new Scanner (System.in);
   System.out.println("What is your number?");
   long limit = x.nextLong();
   long count = 0;

   //making all the numbers upto the given number prime
   boolean arr[] = new boolean [limit]; 
   for ( long i = 2; i <=Math.sqrt(limit); i++) 
   {
       arr[i] = true;
   }
Limbo
  • 101
  • 1
  • 12
  • Even if you could do it, do you realize how much RAM this would consume? Maybe an array is simply not appropriate in this case. – sstan Jun 30 '15 at 17:47

2 Answers2

1

This because you are using a long as a size for an array.

Java supports array up to a certain limit which is around Integer.MAX_VALUE - x (see this) so using a long to specify the size is not allowed.

Quoting from JLS:

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Then how do I store my desired number in the array? If I am changing the long to int, i am getting a java.util.mismatch exception. I read similar problems and found that I maybe able to use 2D arrays or ArrayList but I am fairly new to java so I am not sure how to – Limbo Jul 01 '15 at 08:12
0

Array lengths and indices must always be ints. You cannot create an array with long length, nor can you refer to a long index in an array.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • but what if the input exceeds the limits of ints? like if the input is something like 123456789101112, then I am getting a java.util.mismatch exception – Limbo Jun 30 '15 at 17:41
  • Then you can't use an array. You'll have to use some other data structure or algorithm. – Louis Wasserman Jun 30 '15 at 17:43