-1

I use this code in my class. but its shows the error. why we cant assign long value in the String array declaration? It showing possible loss converstion.

long n=10000000;
String ar[]=new String[n];
  • try String[] ar=new String[n]; – Buda Gavril Oct 16 '15 at 06:47
  • Nearly duplicate of http://stackoverflow.com/questions/1071858/java-creating-byte-array-whose-size-is-represented-by-a-long which clearly indicates that you can only use int for array length- – Sebastian Oct 16 '15 at 06:52

2 Answers2

1

This is correct declaration. Use int instead of long. The Java JVM does not allow creating array in the size, range of long data type, so it is producing the warning (error) at the compile time.

int n=10000000;
String ar[]=new String[n];

I tried the following code:

public class Array {
  public static void main(String args[]) {
    int a[] = new int[Integer.MAX_VALUE];
  }
}

Got the following exception: Requested array size exceeds VM limit

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at gen2dArray.main(Array.java:7)
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
  • 1
    why i cannot assign long value. if my n value is very big like long value. then i need to assign long value in string array. but it wont take it. – Revatha Ramanan K Oct 16 '15 at 06:50
  • @Ram I think it will throw `OutOfMemoryError:` error. Check this out: [Do Java arrays have a maximum size?](http://stackoverflow.com/questions/3038392/do-java-arrays-have-a-maximum-size). – YoungHobbit Oct 16 '15 at 06:51
  • it wont throw any exception. i cannot run it. because while typing it showing error in the netbeans and eclipse also. – Revatha Ramanan K Oct 16 '15 at 06:52
  • @Ram because the compiler is warning you in advance. Even if you create an array of Integer.MAX_VALUE then will not warn you but fail at the runtime. – YoungHobbit Oct 16 '15 at 06:54
  • 1
    @Ram The Java Language specification prevents you from using `long` to declare the size of arrays – MadProgrammer Oct 16 '15 at 06:57
1

This question is likely the same as this

create an array of long

It is related to memory allocation. But we can use multi dimensional array to handle this.

On maximum integer array of string will take a huge amount of Memory.

Try use HashMap if you need to use large of array.

Community
  • 1
  • 1
Kosmas
  • 353
  • 4
  • 11