Ekaba Bisong Ekaba Bisong - 1 month ago 9x
Java Question

How to Instantiate an Array of type long - JAVA

The following code fails to compile:

import java.util.*;

public class test {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long x = sc.nextLong();

long[] array = new long[x];

It produced the error:
error: incompatible types: possible lossy conversion from long to int

I need clarification on the right way to dynamically instantiate an array of type long. Thanks in advance.


You are creating an array with a size of type long (x) but Java expects an integer for an array capacity (because of size, long can be too large for an array).

Thus, Java must convert a long to an int, causing the error telling you it may lose data. 64 bits (long) to 32 bits (int) can be lossy if the long being converted is <32 bits. Change it to:

int x = sc.nextInt();
long[] array = new long[x];

This uses an integer as the capacity instead of a long.