Ekaba Bisong Ekaba Bisong - 1 year ago 127
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download